4

我想要以下设置:

abstract class Parent {
    public static String ACONSTANT; // I'd use abstract here if it was allowed

    // Other stuff follows
}

class Child extends Parent {
    public static String ACONSTANT = "some value";

    // etc
}

这在java中可能吗?如何?如果可以避免的话,我宁愿不使用实例变量/方法。

谢谢!

编辑:

常量是数据库表的名称。每个子对象都是一个迷你 ORM。

4

2 回答 2

18

你不能完全按照你的意愿去做。也许可以接受的妥协是:

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

class Child extends Parent {
    public static final String ACONSTANT = "some value";
    public String getACONSTANT() { return ACONSTANT; }
}
于 2010-10-12T02:36:26.610 回答
2

在这种情况下,您必须记住在 java 中您不能覆盖静态方法。发生的事情是它隐藏了这些东西。

根据您输入的代码,如果您执行以下操作,答案将为空

Parent.ACONSTANT == null ; ==> true

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

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

只要您使用 Parent 作为引用类型 ACONSTANT 将为空。

让你做这样的事情。

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

输出将为空。

于 2010-10-12T03:57:37.187 回答