I want to have the following setup:
我想要进行以下设置:
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
}
Is this possible in java? How? I'd rather not use instance variables/methods if I can avoid it.
这在Java中可行吗?怎么样?如果我可以避免它,我宁愿不使用实例变量/方法。
Thanks!
谢谢!
EDIT:
编辑:
The constant is the name of a database table. Each child object is a mini ORM.
常量是数据库表的名称。每个子对象都是一个迷你ORM。
2 个解决方案
#1
18
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; }
}
#2
2
In this case you have to remember is in java you can't overried static methods. What happened is it's hide the stuff.
在这种情况下你必须记住在java中你不能覆盖静态方法。发生了什么事是隐藏的东西。
according to the code you have put if you do the following things answer will be null
根据您放置的代码,如果您执行以下操作,则答案将为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.
只要您使用Parent作为引用类型,ACONSTANT将为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.
输出将为null。
#1
18
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; }
}
#2
2
In this case you have to remember is in java you can't overried static methods. What happened is it's hide the stuff.
在这种情况下你必须记住在java中你不能覆盖静态方法。发生了什么事是隐藏的东西。
according to the code you have put if you do the following things answer will be null
根据您放置的代码,如果您执行以下操作,则答案将为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.
只要您使用Parent作为引用类型,ACONSTANT将为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.
输出将为null。