Inherit a Static Variable in Java

旧街凉风 提交于 2019-12-01 20:51:51

you can't do it exactly as you want. Perhaps an acceptable compromise would be:

abstract class Parent {
    public abstract String getACONSTANT();
}

class Child extends Parent {
    public static final String ACONSTANT = "some value";
    public String getACONSTANT() { return ACONSTANT; }
}

In this case you have to remember is in java you can't overried static methods. What happened is it's hide the stuff.

according to the code you have put if you do the following things answer will be null

Parent.ACONSTANT == null ; ==> true

Parent p = new Parent(); p.ACONSTANT == null ; ==> true

Parent c = new Child(); c.ACONSTANT == null ; ==> true

as long as you use Parent as reference type ACONSTANT will be null.

let's you do something like this.

 Child c = new Child();
 c.ACONSTANT = "Hi";
 Parent p = c;
 System.out.println(p.ACONSTANT);

Output will be null.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!