9.4 Anonymous class

Hello everyone, in the last video we talked about the internal class and in this video we will talk about the anonymous class. So, an anonymous class is an internal class without a name, hence the term anonymous. So, a single object is created from one when we use it and that object can have extras or modifications and it is really not necessary to create an internal class because we only use it once. And the reason for using an anonymous class is that it helps us avoid cluttering the code with a separate class name. The syntax is very similar to using a constructor except that there is also a class definition that comes next. To better understand, we will make an example. So, we go to our source folder and click on the file then new class and call this class maybe Salutation. Then, we will just display a welcome message in this class. So we’re going to create a public method that doesn’t return anything we’re going to call it "Welcome". and then we’ll just display a message such as «Hello world» for example. Ok now in the main class. create an instance of this class of "Greeting" So, normally we write the class name "Greeting" and then find a name for this object that will be "Greeting" equal to new Greeting and then we can use this method by writing "Greeting.Welcome" and when we execute it it displays «Hello world». Now we can use an anonymous class So what we are going to do, before the semicolon of the class instance "Greeting" we are going to add a set of hugs. Now it’s like a whole new class definition. We can actually copy the "Welcome" method from the Salutation class paste it here and what I’m going to do now is maybe change this message and now if we were to run this this welcome feature will actually display "Hello" Because it is as if we have override this welcome method in our "hi" function Now what would happen if we create another instance of the Salutation class but we will not use anonymous class name the object will be «salut2» and then we’ll use the “welcome” method. So, it will be salut2.welcome and run the program. So the «hello» Hello. And salut2 will be «Hello World» this is normal since the instance does not use the anonymous class This is therefore one of the uses of the anonymous classes, because you can make extras or modifications to a specific object and it’s really useful if you don’t want to create an internal class in another class. And if you really only need to use it once. I thought that was it for this video. I hope you have pretty much understood. What is the anonymous class? I’ll see you next time.