class Parent
{
public static String sName = "Parent";
static
{
System.out.println("Parents static block called");
sName = "Parent";
}
}
class Child extends Parent
{
public static String sName1;
static
{
System.out.println("Childs static block called");
sName = "Child";
sName1 = "Child";
}
}
public class Inheritance
{
public static void main(String []args)
{
System.out.println(Child.sName);
System.out.println(Parent.sName);
}
}
In the above code snippet I have a 'Parent
' class and a 'Child
' class which extends Parent. I understand the fact that static variables are shared between
parent and all of its subclasses. When I run the above program the output is
Parents static block called
Parent
Parent
I wonder why the Child's static block isn't executed even after executing 'System.out.println(Child.sName);
'. I am not sure why only the parent class gets loaded and not the Childs class. Now when I modify the main()
function as shown below the Child's class gets loaded.
public static void main(String []args)
{
System.out.println(Child.sName);
System.out.println(Parent.sName);
System.out.println(Child.sName1); //sName is declared in Child class.
System.out.println(Parent.sName);
}
The output now is shown below and is as expected. Now the Child class has to get loaded as we are making a reference to the static variable sName1 which is declared in Child class.
Parents static block called
Parent
Parent
Childs static block called
Child
Child
The static variable 'sName
' now has 'Child
' as its value. My question here is why doesn't the Child class gets loaded even after making a reference in the first line itself in the main function before modifying it?
Please advise.