1. Anonymous inner class: In fact, it is the simplified form of the inner class, which embodies the subclass object of a class or interface.
Premise:
An inner class must inherit or implement an external class or interface.
Format:
New Parent Class & Interface () {};
is actually a subclass object, with {}; end
There are three types of anonymous internal classes that are represented in the program:
1. The parent class is a normal class
classinter{}classoutertest{ Public Static voidfunction () {NewInter () {Private intnum = 9; voidShow () {System.out.println ("This is a member variable of the Inter subclass Num=" +num); }}.show (); /*If you change the code above: Compile time will be error, because the compile-time check the left type Inter class does not have the show () method Inter in = new Inter () {}; In.show (); */ }}classmyouterdemo{ Public Static voidMain (string[] args) {outertest.function (); }}
2. The parent class is an abstract class (you must override the abstract method in a subclass)
2. The parent class is an abstract class (you must override the abstract method in a subclass)Abstract classtest{Abstract voidshow ();}classouter{intx = 8; /*This is the complete form of the anonymous inner class, class Inter extends test{void Show () {System.out.println (x); } } */ Public voidmethod () {//new Inter (). Show ();Test T=NewTest () {voidShow () {System.out.println ("X=" +x); System.out.println ("This is a method that overrides the test abstract class because the subclass inherits it and must overwrite the"); } voidShow1 () {System.out.println ("This is the test subclass's own method."); } }; T.show (); //T.show1 (); Run this error, because there is no Show1 () method in the test abstract class }}classOuterinterdemo { Public Static voidMain (string[] args) {NewOuter (). method (); }}
3. Parent class is interface interface
Interfaceinter{voidshow ();}classouter{StaticInter Method () {return NewInter () { Public voidShow () {System.out.println ("Show Run"); } }; }}classOuterTest1 { Public Static voidMain (string[] args) {Outer.method (). Show (); /*the above sentence is equivalent to: Inter in = Outer. Method (); In.show (); */ }}
When do I use anonymous internal classes?
When a function's argument is an interface type, the method in the interface is no more than 3 (because the method that produces the anonymous inner class becomes too bloated when the method is too large), in order to simplify the code, the anonymous inner class is passed as a parameter.
Java Learning Note DAY06---anonymous inner class