-2
子类如何更改父类实例变量的值。我在子类中使用super.variable名称尝试过它,但是当我打印父类时。变量名我可以看到变化没有反映在父变量中子类可以如何更改父类实例变量的值
子类如何更改父类实例变量的值。我在子类中使用super.variable名称尝试过它,但是当我打印父类时。变量名我可以看到变化没有反映在父变量中子类可以如何更改父类实例变量的值
更新父变量与parent.variable
是OOP的错误思想。当你扩展父类时,想像你的子类与父类一样,它们不再分离,所以从现在开始想像变量是孩子的。但是只是切片差异是public
private
定义它设置每个类的项目的可见性。因此,在下面的示例中,我只为父级定义了一个私有变量,以便孩子无法看到它,但孩子能够通过公共getter setter更新变量。这是因为我们使用getter和setter来提供封装,因为它只与Parent类有关。请调查代码以了解更多:
class Main {
public static class Parent {
private int variable;
public int getVariable() {
return variable;
}
public void setVariable(int variable) {
this.variable = variable;
}
}
public static class Child extends Parent {
private int childVadiable;
public Child() {
}
public int getChildVadiable() {
return childVadiable;
}
public void setChildVadiable(int childVadiable) {
this.childVadiable = childVadiable;
}
public void updateParentVariable(int value) {
this.setVariable(value);
}
}
public static void main (String[] args) {
Child child = new Child();
child.updateParentVariable(5);
System.out.println(child.getVariable());
//Result it '5'
}
}
你能显示代码吗? – Jeet
我想你应该使用Java书籍而不是stackoverflow ... – Jay
孩子已经从其父母继承(公共和受保护的)变量,因此您可以通过使用this.variable访问和更改它。 – Raptor