Вопрос

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!

Это было полезно?

Решение 2

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);
    }
} 

Другие советы

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.

Yes, this is fine. If the superclass doesn't want subclasses modifying values, it can make them private.

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.

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top