Illustrate Class Loading and Static Blocks in Java Inheritance
Class loading means reading .class file and store corresponding binary data in Method Area. For each .class file, JVM will store corresponding information in Method Area. Now incorporating inheritance in class loading. In java inheritance, JVM will first load and initialize the parent class and then it loads and initialize the child class.
Loading class A 1st static block Loading class A 2nd static block B.c=0 Loading class A 3rd static block Loading class B static block A.a=50
From the above output. it can be said that the parent class loads before the child class and also child class initialize after the parent class. One can check this by executing it with java -verbose Test.
The static block will be executed at the time of class loading, hence at the time of class loading if we want to perform any activity we have to define that inside the static block. In static block inheritance one must remember the following two rules as follows:
- One can not override a static block as the non-static else compile-time error will be generated.
- Non-static block can not be overridden as a static block.
Usage of the static block in inheritance is as shown below for the above scenarios as the compiler error that will be generated is shown below for both the cases individually as follows:
Case 1: One can not override a static block as the non-static else compile-time error will be generated
Case 2: Non-static block can not be overridden as a static block
Note: No compile-time error will be generated only and only if both parent and child class methods are static.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.