+ 4

Where can we use the anonymous-classes and is it really important?

I mean when to use it and when to call it in a code.It is quite confusing and more explanation is required for this topic.

12th Jan 2017, 2:08 PM
Munindra
Munindra - avatar
1 Answer
+ 2
The primary use for anonymous classes is to implement an interface without creating a whole new class to do so. In other words, it's used to create an instance of a class that only has a one time use and so would not make use of being it's own fully defined class. It's also often used as a way to pass a method as if it were a parameter to an object. As an example: new Thread(new Runnable() { public void run(){ method1(); } }).start(); This code creates a new thread, passing it a Runnable object, which is an instance of an anonymous class which implements Runnable. The thread starts, invoking the run method in the anonymous class and calling method1(); Effectively, the new runnable object can be seen as the equivalent of method1. This is similar to how other programming/scripting languages can store functions inside of variables to pass around.
17th Jan 2017, 6:01 AM
Thomas McSherry
Thomas McSherry - avatar