Skip to content
Advertisement

Should I keep an enum attribute when it has always the same value as a result of a new inheritance?

I have these classes:

JavaScript
JavaScript

Imagine that for some reason, I need to make Car a superclass for two new classes: CombustionCar and ElectricCar. One of the new requierements is that ElectricCar’s brand attribute must be always TESLA value and not any of the other ones values. I’ve thougth some solutions:

  1. I could keep Brand attr on superclass Car, and make ElectricCar constructor to set TESLA brand. But this way could allow me to set a new Brand after creating the object
JavaScript
  1. I can take Brand attr out from superclass and set it on both subclasses, but setting it in ElectricCar as a class attribute with a final so anyone would be able to set a new value
JavaScript
  1. Avoid inheritance and use composition, but with this I wont be able to use, for example, a List which contain both:
JavaScript

I’m asking for the most elegant and manteinable solution, I think any of them would be nice to resolve my problem.

Advertisement

Answer

Your first solution is incorrect given that you required a non editable BRAND for an electric car.

Your second solution just doesn’t work at all excepted if you override both getter and setter of brand field to use your static field, which is not “elegant and mantainable”

Your third solution doesn’t make use of object oriented concept.

A simple solution I would use is to let the field brand and its getter in Car superclass, but I’d only define the setter in the CombustionCar class. Alternatively, if you extend your model, you could create an intermediate abstract superclass “FreeBrandCar” which implements the setter.

Solution with the setter in CombustionCar

JavaScript

Solution with an intermediate class

JavaScript

It respects your requirements :

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement