I will write this article by myself, because anonymous internal classes are the most difficult to understand in the internal class series.
A. inherited anonymous internal class.
Reference reprinted code:
The result is output: driving another car! The car reference variable is not a reference car object, but an object of the car anonymous subclass.
The key to building an anonymous internal class is to override one or more methods of the parent class. It is emphasized that the method of rewriting the parent class, rather than creating a new method. Because it is impossible to call methods that the parent class does not have by referencing the parent class! Creating a new method is unnecessary. In short, refer to polymorphism.
You may be confused here, especially
Car car = new car () {public void drive () {system. Out. println ("driving another car! ");}};
Let me explain this code: It is equivalent
Their difference is that the xxx name is not needed here.
B. Anonymous internal classes of abstract classes and interfaces.
The above is an abstract class code, the interface is almost identical with the abstract class, just change abstract to interface.
C. Parameter-Based Anonymous internal class
Reference reprinted code:
If you can understand both A and B, you don't need to explain it here.
Summary: The core of anonymous internal classes is "inheritance" and "Implementation". Because internal classes do not have constructor methods, the initialization of internal classes is only "code block ".
You just need to think about how the abstract class and interface will be new out of the instance? Must be their subclass.