Update fields from superclass

吃可爱长大的小学妹 提交于 2019-12-12 00:07:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!