Let's see if the following code can be compiled by:
public static void Main (string[] args) {
List L1 = new ArrayList ();
List L2 = new ArrayList () {};
List L3 = new ArrayList () {{}};
System.out.println (l1.getclass () = = L2.getclass ());
System.out.println (l2.getclass () = = L3.getclass ());
System.out.println (l1.getclass () = = L3.getclass ());
}
The answer is to compile and output 3 false. L1 It is easy to understand, is to declare a
ArrayList object, then what is L2, L3?
L2 is an anonymous class internal class object, inheriting ArrayList;
The L3 statement is a bit odd, with two curly braces, which we'll understand, which is also the definition of an anonymous inner class, and its code looks something like this:
Class Sub extends ArrayList {
//initialization code block
}
}
List L3 = new Sub ();
See, it is more than one initialization code block, play the function of the constructor. Of course a building code block in a class can have multiple, and the following code can be compiled:
List L4 = new ArrayList () {{}{}{}};
An anonymous inner class can act as a constructor with an initialization block of code, but its constructors have special processing that invokes the same parameter constructor of the parent class directly when it is initialized, and then calls its own code block, for example:
List l5 = new ArrayList (5) {
{
System.out.println ("I am an anonymous inner class ');
}
;
Equivalent to:
Class Sub extends arraylist{
{
System.out.println ("I am anonymous inner class");
}
Sub (int num) {
super (num);
}
}
List l5 = new Sub (5);
Let's take a look at the snippet sample code
Package testtest;
public class Main {public
static void Main (string[] args) {
innertest inner = new Innertest ();
Test t = inner.get (3);
System.out.println (T.geti ());
}
Class Test {
private int i;
Public Test (int i) {
this.i = i;
}
public int Geti () {return
i;
}
}
Class Innertest {public
Test get (int x) {return
new Test (x) {
@Override public
int Geti () {
ret Urn Super.geti () *;}
}
Gets 4 class files after compilation: Test.class,innertest.class,innertest$1.class and Main.class. It is easy to see, Main.class is the class file of test classes, Test.class is the class file of the superclass test, Innertest.class is the Innertest class file, The most noteworthy is the anonymous inner class file Innertest$1.class.