Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 334
E. Rowlands Avatar asked Sep 06 '25 02:09

E. Rowlands


1 Answers

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.

like image 189
Eugene Avatar answered Sep 07 '25 21:09

Eugene