Anonymous internal class constructor analysis, Anonymous class Constructor

Source: Internet
Author: User

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 );

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.