Illustrate Class Loading and Static Blocks in Java Inheritance
Last Updated :
08 Jun, 2021
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.
Example
Java
import java.io.*;
class A {
static
{
System.out.println(
"Loading class A 1st static block " );
}
static
{
System.out.println(
"Loading class A 2nd static block B.c="
+ B.c);
}
static
{
System.out.println(
"Loading class A 3rd static block " );
}
static int a = 50 ;
A() {}
}
class B extends A {
static
{
System.out.println(
"Loading class B static block A.a=" + A.a);
}
static int c = 100 ;
}
class GFG {
public static void main(String[] args)
{
new B();
}
}
|
Output
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
Example
Java
import java.io.*;
class GFG {
public static void m1() {}
}
class c extends GFG {
public void m1() {}
}
|
Output:
Case 2: Non-static block can not be overridden as a static block
Example
Java
import java.io.*;
class GFG {
public void m1() {}
}
class C extends GFG {
public static void m1() {}
}
|
Output:
Note: No compile-time error will be generated only and only if both parent and child class methods are static.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...