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