+ 17

What is anonymous class in Java?

11th Mar 2017, 8:40 AM
Ajay Agrawal
Ajay Agrawal - avatar
4 Respuestas
+ 21
A class that is used without declaring an object /variable name for it. Example: https://code.sololearn.com/cWXx7MZCk8Q3/?ref=app This example shows how it works, but a better example to use anonymous classes is Thread: public class HelloThread extends Thread { public void run() { System.out.println("Hello from a thread!"); } public static void main(String args[]) { (new HelloThread()).start(); } } from https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html You see, that the started thread has no name. You can use anonymous classes, when you don't need to access the object after creating it.
11th Mar 2017, 9:03 AM
Tashi N
Tashi N - avatar
+ 15
Anonymous: (new HelloThread()).start(); Here only the constructor is called, which returns an instance of the class and then calls start method. Without assigning a name to the object. Named variable: HelloThread hello = new HelloThread(); hello.start(); Does the same with a variable named hello. Hope this helps.
11th Mar 2017, 6:22 PM
Tashi N
Tashi N - avatar
+ 10
that was confusing for me, sorry but I don't understand z😑
11th Mar 2017, 2:53 PM
Ajay Agrawal
Ajay Agrawal - avatar
+ 4
Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.
12th Mar 2017, 3:25 PM
Coding Girl
Coding Girl - avatar