Java knowledge accumulation-static code blocks, non-static code blocks, execution sequence and times of Constructors

Source: Internet
Author: User

See the following program:

 1 class A { 2    static{ 3       System.out.println("A static"); 4    }    5  6    { 7       System.out.println("A not static");  8    }    9 10    public A(){11       System.out.println("A new");12    }13 }14 15 class B extends A{16    static{17       System.out.println("B static");18    }   19 20    {21       System.out.println("B not static"); 22    }  23 24    public B(){25       System.out.println("B new");26    }27 } 28 29 public class MainTest {30    public static void main(String[] args) {31       A ab= new B();32       ab= new B();33    }34 }

The output is as follows:

A static

B static

A Not static

A new

B Not static

B New

A Not static

A new

B Not static

B New

 

Conclusion: 

A static code block is called only once when the class is loaded into the memory for the first time.

Non-static code block. Each time an object is created, it is called before the constructor.

Constructor, called at the end of each object creation.

Create a parent class object before creating a subclass object.

Related Article

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.