Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

java - Behavior of static blocks with inheritance

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As I understand. You don't call any Derived properties (myVar belongs to Base, not to Derived). And java is not running static block from Derived. If you add some static field to Derived and access it, then java executes all static blocks.

class Base {

    static public int myVar;

}


class Derived extends Base {

    static public int myVar2;

    static
    {
        Base.myVar = 10;
    }
}


public class Main {
    public static void main( String[] args ) throws Exception {
        System.out.println(Derived.myVar2);
        System.out.println(Base.myVar);
    }
}

From java specification, when class is initialized (and static block got executed):

12.4.1 When Initialization Occurs A class or interface type T will be initialized immediately before the first occurrence of any one of the following:

? T is a class and an instance of T is created.
? T is a class and a static method declared by T is invoked.
? A static field declared by T is assigned.
? A static field declared by T is used and the field is not a constant variable (§4.12.4).
? T is a top level class (§7.6), and an assert statement (§14.10) lexically nested within T (§8.1.3) is executed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...