简体   繁体   中英

static members throught static methods

Given:

public class Base {
    public static final String FOO = "foo";
    public static void main(String[] args) {
        Base b = new Base();
        Sub s = new Sub();
        System.out.print(Base.FOO);       // <- foo
        System.out.print(Sub.FOO);        // <- bar
        System.out.print(b.FOO);          // <- foo
        System.out.print(s.FOO);          // <- bar
        System.out.print(((Base)s).FOO);  // <- foo
    } 
}

class Sub extends Base {
    public static final String FOO="bar";
  }

My doubt is that in line 8 and line 9 we are using reference variables to access static members of class... is it possible? Because static members are accessed by class names only... Please correct me where i am wrong?

I'm going option D.

Static members are resolved at compile time using the declared type, not the actual type.

That's why ((Base)s).FOO) refers to Base.FOO - even though the object is a Sub .

This would also occur, and is better illustrated, in the following:

Base b = new Sub(); // valid
System.out.print(b.FOO); // foo

Here b.FOO refers to Base.FOO because of the declared type, even though the instance is a Sub .

is it possible?

Yes it's possible, although not a good practice. Basically, accessing the static member on field is resolved at compile time as access on the declared type of the field.

For example, even the below case would work fine:

class Test {
    public static String hello = "Hello";
}

Test test = null;
System.out.println(test.hello);

The print statement will not throw NPE , as you would expect it on first look. Because the access is effectively resolved to:

Test.hello

Since the declared type of test is Test , the access is resolved this way.


Now since the static field access is resolved using the declared type at compile time, for this reason you won't see polymorphic behaviour for static methods. It goes like, you can't override static methods.

Static members can be accessed by instances as well.

IMO it's a Bad Practice because it's misleading/uncommunicative.

In fact, you can use a null reference, eg,

Base base = null;
System.out.println(base.FOO);

You can access static variables via references. But normaly you should get a warning from your compiler....

Static variables can be accessed by class name as well as by a reference. Refer to Access static variable from object in Java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM