I am trying to use static blocks like this:
I have a base class called Base.java
public class Base {
static public int myVar;
}
And a derived class Derived.java
:
public class Derived extends Base {
static
{
Base.myVar = 10;
}
}
My main
function is like this:
public static void main(String[] args) {
System.out.println(Derived.myVar);
System.out.println(Base.myVar);
}
This prints the out put as 0 0
where as I expected 10 0
. Can somebody explain this behavior? Also, if I want my derived classes to set the values for a static variable how can I achieve that?
Static initializer-blocks aren't run until the class is initialized. See Java Language Specification paragraphs 8.7 (Static initializers) and 12.4.1 (When initialization occurs):
Here's a similar example straight out of JLS 12.4.1:
Here is the link to the Java Specification - section 8.7 talks about static initializers. It gives good details about how they should function and the order in which they get called. http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.7
There is a single copy of
myVar
and both parent and child class will share the same. Untill and unless child class get initilized.When we do
The Output will be
Base 0 0
That means derived class's static block not executing..!!
As I understand. You don't call any
Derived
properties (myVar
belongs toBase
, not toDerived
). And java is not running static block fromDerived
. If you add some static field toDerived
and access it, then java executes all static blocks.From java specification, when class is initialized (and static block got executed):