本文介绍了更新超类的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从各种模式的角度来看,可以从其后代更改超类中的字段。例如:
From point of various patterns is it acceptable to change fields in superclass from its descendants. For example:
class A {
int barA;
}
class B extends A {
private void testMethod() {
barA = 4;
}
}
谢谢!
推荐答案
不,通常不是一个好主意。如果我理解您的要求,通常可以这样做
No, it's generally not a good idea. If I understand what you are asking, it would normally be done like
public class A{
private int val;
protected void setVal(int i){
val = i;
}
public int getVal(){
return val;
}
}
public class B extends A{
public void test(){
this.setVal(4);
}
}
这篇关于更新超类的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!