Static Block, Instance, Block, Constructor Chainning

If I have static block, instance block and constructor chaining from super class to sub class then below will be the order of execution:

super class static block --> sub class static block --> super class instance block --> super class constructor --> sub class instance block --> sub class constructor

class A {
public A() {
System.out.println("A1 constructor code");
}

{
System.out.println("A2 instance block");
}

static {
System.out.println("A3 static block");
}
}

class B extends A {
public B() {
System.out.println("B1 A1 constructor code");
}

{
System.out.println("B2 instance block");
}

static {
System.out.println("B3 static block");
}
}

class C extends B {
int id;

public C() {
System.out.println("C1 A1 constructor code");
}

{
System.out.println("C2 instance block");
}

static {
System.out.println("C3 static block");
}
}

public class StaticAndInstanceBlockExample {

public static void main(String[] args) {
C c = new C();
}
}

Output:
A3 static block
B3 static block
C3 static block
A2 instance block
A1 constructor code
B2 instance block
B1 A1 constructor code
C2 instance block
C1 A1 constructor code

Comments

Popular posts from this blog

SQL basic interview question

gsutil Vs Storage Transfer Service Vs Transfer Appliance