Java Interview Basics------"Parent-child class static code block in Java, code block, construction method execution order

Source: Internet
Author: User

4 , indicating the running result of the following program.

Class A {

static {

System.out.print ("1");

}

Public A () {

System.out.print ("2");

}

}

Class B extends a{

static {

System.out.print ("a");

}

Public B () {

System.out.print ("B");

}

}

public class Hello {

public static void Main (string[] args) {

A ab = new B ();

AB = new B ();

}

}

A: Execution result: 1a2b2b. When you create an object, the constructor is called in the order that it initializes the static member, then calls the parent class constructor, initializes the non-static member, and finally calls itself the constructor.

The following demo:

Parent.java

/** * @author: Snowing * @date  : April 18, 2017 *  */public class Parent {static {        System.out.println ("Parent ' s static code block ");    }        {        System.out.println ("Parent ' s code block");    }        Public parent () {        System.out.println ("Parent ' s constructor method");}    }

Child.java

/** * @author: Snowing * @date  : April 18, 2017 *  */public class Child extends Parent{static {        System.out.print ln ("Child ' s Static code block");    }        {        System.out.println ("Child ' s code block");    }        Public Child () {        System.out.println ("child ' s construction method");    }    public static void Main (string[] args) {    new Child ()}}

Output:

Java Interview Basics------"Parent-child class static code block in Java, code block, construction method execution order

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.