Java – will this implementation be called an anonymous class?
I've seen it many times, but I'm a little confused. Will it be called anonymous class?
public class Test { public static void main(String[] args) { new Thread(){ @Override public void run() { Sy@R_301_2354@.out.println("##"); } }.start(); } }
The reason why I am confused is that the anonymous class has no name, but obviously we already have a "thread" class in the Java API, so it means that it has a name. If it has a name, how is it anonymous? If it is not an anonymous class, what is it
I know it's stupid, but I can't reason my own certainty - because I see that both sides have the right arguments
In addition, I can clearly override the run method of thread class above. Now if I create my own class, let's say MyClass, define some methods in it, and then try to do the same thing. Then why can't I override the method of MyClass? They can override the run method of thread class
public class MyClass { private void myMethod1() { } private void myMethod2() { } } public class Test { public static void main(String[] args) { new MyClass(){ // why I cannot override "myMethod1" and "myMethod1" of `MyClass`,they way I was able to override `run` method of `Thread` class }; } }
Solution
>Yes, your first class is anonymous because it is inline and extends from thread It is different from the thread class
To clarify, if you have a nested class with a name, you can declare variables of its type:
public class Test { private static class MyThread extends Thread { @Override public void run() { Sy@R_301_2354@.out.println("Foo"); } } public static void main(String[] args) { MyThread myThread = new MyThread(); } }
But if you have an anonymous class, you can't do this:
public static void main(String[] args) { new Thread(){ @Override public void run() { Sy@R_301_2354@.out.println("##"); } }.start(); // how can you declare a variable of the above type *with* its behavior? }
Edge: you should hardly extend thread, but implement runnable, or even better, use executors to help you thread
Reply:
Yes, you did create a new class, but it's not that you don't have to implement an interface In fact, the above example is not directly related to the interface, but related to extending existing concrete classes You can and often create anonymous classes that implement interfaces. Runnable is a common example, but the above example is not "basically an interface implementation"