Anonymous internal class constructor analysis, Anonymous class Constructor
First, let's see if the following code can be compiled:
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 that three false values can be output through compilation. L1 is easy to understand, that is, it declares
What is an ArrayList object l2 and l3?
L2 is an internal class object of an anonymous class and inherits the ArrayList;
The l3 statement is a bit odd and contains two braces. In fact, we can understand it in this way. This is also the definition of an anonymous internal class. Its code is similar to the following:
Class Sub extends ArrayList {
{
// Initialize the code block
}
}
List l3 = new Sub ();
As you can see, there is only one more initialization code block to function as a constructor. Of course, there can be multiple constructed code blocks in a class, and the following code can be compiled:
List l4 = new ArrayList (){{}{}{}};
Although an anonymous internal class can use an initialization code block to act as a constructor, its constructor performs special processing. during initialization, it directly calls the constructor with the same parameters of the parent class, then, call your own code block, for example:
List l5 = new ArrayList (5 ){
{
System. out. println ("I am an anonymous internal class ");
}
};
It is equivalent:
Class Sub extends ArrayList {
{
System. out. println ("I am an anonymous internal class ");
}
Sub (int num ){
Super (num );
}
}
List l5 = new Sub (5 );