Update fields from superclass

From the point of various patterns, it is acceptable to change the fields in the superclass from their descendants. For instance:

class A { int barA; } class B extends A { private void testMethod() { barA = 4; } } 

Thanks in advance!

0
source share
5 answers

No, this is not a good idea at all. If I understand what you are asking, this is usually done as

 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); } } 
+3
source

As a general rule, it's best to make all your fields private and provide public or secure setters if you want to change their value in subclasses.

+4
source

Yes, that's great. If a superclass does not want subclasses to change values, it can make them private.

+2
source

When we say that class B extends A, we mean that it inherits all of its (superclass, for example, A) variables. So now B has its own barA variable. That way you can change it just like any other member variable. Read this later .

+1
source

This is fine, but instead, why don't you create getter/setter for the same? It is much better to use them instead of directly changing.

If you do not need the values ​​changed in the subclass, make them final .

0
source

Source: https://habr.com/ru/post/956969/


All Articles