Why does an abstract subclass of a particular bad class design arise?

After all, ANY java abstract is an abstract subclass of Object. Sometimes we need to force a subclass to implement some methods, but it may already have a fairly well-defined hierarchy with specific classes.

For example: I have a well-functioning hierarchy with Car <--- Car

and now I want to add ElectricCar to this hierarchy.

Car <- Car <- ElectricCar.

I also want all the different types of electric vehicles to use certain types of behavior like getBatteryLife or something -

Why would it be a bad idea to make ElectricCar abstract?

+4
source share
5 answers

there is nothing wrong with making it abstract. if your business requires you to make it abstract, that's fine. As you said, many classes in Java lib are abstract and still extend Object.

+2
source

This is not bad in itself. Not general, but not bad. The only thing I can think of is understandability: if I saw a specific Car class that could instantiate, I would usually assume that any of its children would also be real, because 99% of the code works this way. Then I would be confused, for a second, about the impossibility of creating an instance of ElectricCar.

+1
source

It can be argued that this template violates the Liskov Substituion Principle principle, since you cannot pass the "ElectricCar" wherever the "car" is expected if it declared abstract (you could, of course, pass instances of subclasses of ElectricCar).

In this particular example, the specific electric cars (hydrogen / plugins / etc.) that I would expect to inherit directly from "Car", since they satisfy the "is-a" relationship and are the proper specialization of "Car". If you want to describe some common behaviors and traits that they must provide, then they must also implement the ElectricCar interface.

It seems that you really want this ability to inherit from Car (as that is what they are) and share / repeat common implementations of electric vehicle-related methods. In this case, you are looking at the problem of multiple inheritance or the need for mixins , none of which are directly supported in Java.

Providing an abstract class in the middle of a specific hierarchy may be one way, but it’s not very.

+1
source

Personally, I would prefer to define an interface for ElectricCar, and then let the implementation class define methods. You can then share the behavior of getBatteryLife using another mechanism.

I have built several fairly deep Inheritance hierarchies, and I try to avoid them to the fragile nature with which they tend to grow over time. One base class might make sense, but I was thinking about how you can build your object model to share behavior without inheritance, if possible.

0
source

In your example, I would say that, presumably, the Car class should be abstract (or an interface). But there is nothing wrong with the fact that ElectricCar is abstract.

0
source

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


All Articles