我想拥有以下设置:

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。

有帮助吗?

解决方案

您不能完全按照自己的意愿做到这一点。也许可以接受的妥协是:

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

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

其他提示

在这种情况下,您必须记住的是在Java中,您不能接管静态方法。发生的事情是隐藏东西。

根据您提出的代码,如果您执行以下操作,答案将为无效

Parent.ACONSTANT == null ; ==> true

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

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

只要您将父级用作参考类型constant,则将为null。

让您做这样的事情。

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

输出将为null。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top