Reputation: 331
I have an abstract super class and several subclasses that inherit fields defined in the super class, but each subclass has different values for those fields. When the subclass is called, I use the constructor to set the fields appropriately.
Should I use direct references to do this field = value
, or should I use the super class set methods setField(value);
?
I'd rather keep the fields private, so I want to avoid direct references.
The other alternative is to call the super constructor, which would allow me to use direct references in the super class constructor super (T value)
and in the super class SuperClass(T value){ field = value}
. Would this be the best way? I could even use set methods inside the super constructor, but this seems like it would be redundant.
Upvotes: 0
Views: 2351
Reputation: 163
One great advantage and one great reason why abstract superclasses are used is to save coding time and make your class architecture that much easier. Therefore, if you have a superclass that has common fields with subclasses, then you should take a second look at your architecture.
To solve your problem, remove any redundant fields that are in the subclasses but already exist in the superclass. Whenever you want to utilize the fiels, simply use the superclasses reference. Call for instance the superclasses constructor to set the values for the fields etc.
Whenever you want to retrieve the fields, call "super.getValue(...)" etc
Upvotes: 2
Reputation: 10288
In general, you should make them private and access them using getters and setters. If subclasses are allowed to set them directly, they could violate the contracts of the superclass by setting invalid values.
And if the subclasses differ only in the values of those superclass fields, then you shouldn't use subclasses at all; just create instances of the superclass with different values.
Upvotes: 1