+ 17
What is anonymous class in Java?
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.
+ 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.
+ 10
that was confusing for me, sorry but I don't understand z😑
+ 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.