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.