问题
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;
}
}
Thanks in advance!
回答1:
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);
}
}
回答2:
It is generally a better practice to make all your fields private, and provide public or protected setters if you want to change their value in subclasses.
回答3:
Yes, this is fine. If the superclass doesn't want subclasses modifying values, it can make them private.
回答4:
When we say class B extends A, we mean that it inherits all its (superclass' i.e. A's) variables as well. So now B has its own variable barA. Thus you can change it just like any other member variable. Further read this.
回答5:
It is ok to do that but instead why don't you create a getter/setter
for the same ? It is much better to use those instead of modifying directly.
If you do not want the values modified in the subclass, make them final
.
来源:https://stackoverflow.com/questions/19658621/update-fields-from-superclass