Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Accessing static variable from subclass

807580Aug 23 2010 — edited Aug 27 2010
Hi,

this question is probably fairly common but I can't seem to find the answer around: Can somebody please explain the rationale behind the following behavior ?
public abstract class SuperClass {

    static String mess;

}
public class SubClass extends SuperClass {

    static {
        mess = "Hello world!";
    }    

    static String getMess() {
        return mess;
    }
}
public class mymain {

    public static final void main(String[] args) {

        System.out.println(SubClass.getMess());
    }
}
gives "Hello world!" as expected whereas
public abstract class SuperClass {

    static String mess;

    static String getMess() {
        return mess;
    }
}
public class SubClass extends SuperClass {

    static {
        mess = "Hello world!";
    }    
}
public class mymain {

    public static final void main(String[] args) {

        System.out.println(SubClass.getMess());
    }
}
gives "null". It looks like the initialization block is not executed. Why?

Thanks for your insight,
Chris
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Sep 24 2010
Added on Aug 23 2010
24 comments
1,525 views