Changing variable values ​​in subclasses?

It was quite a long time since I was working on something in Java, and I really have very limited experience in creating anything with it at all, for the most part I write at higher levels of these languages, scripting languages ​​and sorting.

I suppose I don't understand the concept of assigning default values ​​to class members.

// parent public class A { protected int value = 0; public void print() { System.out.println(value); } } // child class public class B extends A { int value = 1; } 

To save it, instantiating B and calling print () prints the original value "value" set to A.

I guess it’s probably not some kind of common identifier for a “variable with the name“ value ”belonging to this object,“ a certain function on A has a completely different context for “value” than B. does.

What other method exists for organizing common variations of a certain class, but creating a child of a specified class? Some kind of factory object? Interfaces do not seem to be the answer, because then I need to redefine all aspects of this class, so I won nothing.

Any help would be greatly appreciated, thanks.

+5
source share
2 answers

Subclass fields do not override superclass fields.

You can set the default value through the constructors as shown below.

 // parent public class A { private int value = 0; public A( int initialValue ) { value = initialValue; } public void print() { System.out.println(value); } } // child class public class B extends A { public B() { super( 1 ); } } 

In addition, in most cases your life will be easier if you avoid protected fields.

Protected fields open your data for direct access and modification by other classes, some of which you cannot control. Poor encapsulation can make mistakes and block modification. As suggested in the Java access control guides :

"Use the most restrictive access level that makes sense for a particular member. Use private if you have no good reason."

+6
source

@ user2038045 is a good question.

The source of your confusion is that in Java, a subclass can override methods ... but cannot override member variables.

If your class B had its own print () method, you will see the behavior you expected. B.print () will override A.print ().

If your class B had any other method that accessed the "value", you will again see the behavior that you expected. B.value will hide A.value, and B.someOtherMethod () will access B.value.

But in your case, you called A.print () ... which accesses A.value.

More details:

Is there a way to override class variables in Java?

+4
source

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


All Articles