java 如何在java中设置继承的变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7772700/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set inherited variable in java?
提问by Borut Flis
public class Atribut {
int classid;
@Override public String toString() {
return Integer.toString(classid);
}
}
I have made this class which overrides method toString(). I plan on making many subclasses with different classid. The problem is I dont know how to set the variable classid to work in toString method.
我已经创建了这个类,它覆盖了 toString() 方法。我计划制作许多具有不同 classid 的子类。问题是我不知道如何设置变量 classid 以在 toString 方法中工作。
public class cas extends Atribut{
int classid=2;
}
The problem is if I make an cas object and toString method it returns "0" not "2".??
问题是,如果我创建一个 cas 对象和 toString 方法,它会返回“0”而不是“2”。??
回答by Daniel Pryden
My preferred technique for this kind of thing is to use constructor arguments:
我对这种事情的首选技术是使用构造函数参数:
public class Parent {
// Using "protected final" so child classes can read, but not change it
// Adjust as needed if that's not what you intended
protected final int classid;
// Protected constructor: must be called by subclasses
protected Parent(int classid) {
this.classid = classid;
}
@Override
public String toString() {
return Integer.toString(classid);
}
}
public class Child extends Parent {
public Child() {
// The compiler will enforce that the child class MUST provide this value
super(2);
}
}
回答by Cajunluke
Much as @java_mouse recommended, just use the parent class's variable.
正如@java_mouse 所推荐的那样,只需使用父类的变量即可。
public class Atribut {
protected int classid;
public Atribut() {
classid = 0;
}
@Override
public String toString() {
return Integer.toString(classid);
}
}
public class Cas extends Atribut{
public Cas() {
classid = 2;
}
}
Set classid
's value in the constructor and then you can use the superclass's toString()
just fine.
classid
在构造函数中Set的值,然后你就可以使用超类的toString()
就好了。
回答by corsiKa
When you shadow the variable, the one in the parent class is used in methods there.
当您隐藏变量时,父类中的变量在那里的方法中使用。
If you want to do this, I would do this
如果你想这样做,我会这样做
class Atribut {
int classid = 0;
protected int classid() { return classid; } // points to Attribut.classid
public String toString() {
return Integer.toString(classid());
}
}
Then in your child class, you can override the method
然后在您的子类中,您可以覆盖该方法
class cas {
int classid = 2;
protected int classid() { return classid; } // points to cas.classid
}
回答by java_mouse
Why do you want to shadow a variable in child class if it is already available in the parent? why not using the same variable?
如果父类中已经存在变量,为什么要隐藏子类中的变量?为什么不使用相同的变量?
if you use the same variable, the issue is resolved automatically. Don't duplicate the attribute if it has to be inherited.
如果您使用相同的变量,问题会自动解决。如果必须继承该属性,请不要复制该属性。