Today I came across a code snippet and explanation which is as follows
class Super
{
static int taxi = 1729;
}
class Sub extends Super
{
static
{
System.out.print("Sub "); }
}
class
Test {
public static void main(
String[] args)
{
System.out.println(Sub.taxi);
}
}
Ouuput : 1729
I expected the O/P as
Sub
1729
The explaination given is as follows:
A reference to a class field causes initialization of only the class or interface that actually declares it, even though it might be referred to through the name of a subclass, a subinterface, or a class that implements an interface.
Here the class "Sub" is never initialized; the reference to Sub.taxi is a reference to a field actually declared in class Super and does not trigger initialization of the class Sub.
Ok,coming back to my question,My program is as follows
class parent
{
static int x=5;
static
{
System.out.println("static block in parent");
}
parent()
{
System.out.println("parent's no arg constr");
}
}
class child extends parent
{
static
{
System.out.println("static block in child ");
}
child()
{
System.out.println("no arg constr in child class");
}
}
class staticTest extends child
{
public static void main(String ar[])
{
System.out.println(child.x);
}
}
According to the above explaination,here the statemnt
"child.x" should refer to the class "parent" in which "x" was declared
and 'static" block in it should run printing
"static block in parent" and priint the x value which is 5.
but my actual o/p is
static block in parent
static block in child
5
Why the child class' static block also running here where as
in the code snippet I provided it was not running?