E. Rowlands E. Rowlands - 25 days ago 8
Java Question

For polymorphic classes, is it OK to use protected instance variables?

I have a superclass called

Seat
(for a concert hall).

GoldSeat
,
SilverSeat
and
BronzeSeat
are its subclasses.

I've always read to keep data
private
so as to enable encapsulation.

If I need to write methods that use these instance variables in the subclasses, is it considered acceptable to make them
protected
? Most of the similar stack overflow questions don't address correct object-oriented design, but rather focus on differences between access modifiers and the processing efficiency or technical difference of each. If I missed one, I apologise in advance and will happily review it.

I could use getter methods in the subclasses to get the instance variables, but that seems bizarre in this case, but at least the data would be
private
.

Answer

is it considered acceptable to make them protected?

Yes. I don't think it will break the law of encapsulation when you use protected modifier. Allow only the subclass to access the instance, we still control what should be accessed by others and who can access the instance.

I could use getter methods in the subclasses to get the instance variables, but that seems bizarre in this case

In some cases, you want to do some preprocessing before others can access the instance and you can put the preprocessing in the Getter.