Java – can you extend all subclasses of a class with a single class?
Java – can you extend all subclasses of a class with a single class?
Let's explain it with an example. The actual code is much more complex I have an animal class that has its own class hierarchy Suppose it has two subclasses: testarrosa and viper
public class Car { public abstract String getManufacturer(); } public class TesTarossa extends Car{ public String getManufacturer(){ return "Ferrari"; } } public class Viper extends Car{ public String getManufacturer(){ return "Dodge"; } }
I want to extend all car subclasses with the registeredcar subclass
public class RegisteredCar extends Car { private String plateNumber; public RegisteredCar (String plateNumber){ this.plateNumber=plateNumber; } public String getPlateNumber() { return plateNumber; } }
At some point, I should be able to create a new registeredcar with a special subclass It's like
RegisteredCar c = new RegisteredCar<Viper>("B-3956-AC");
And call c.getmanufacturer() to get "dodge" and c.getplatenumber() to get b-3956-ac. obviously, I can still create a car C = new viper();
This is an example If not registered, the attribute with null value in car is not enough to meet my needs
Solution
As others have said, there are no unlikely ones. Your example can be solved by changing your model
As an alternative to inheritance, you can use another class to wrap the car instance I will make car an interface (although the extension for registering car should also work), and then try pseudo code like the following:
class RegisteredCar<T extends Car> implements Car { private final T car RegisteredCar(T car) { this.car = car; } ... methods for RegisteredCar ... methods from Car delegating to `this.car` }
Please forgive me for some bad code. I didn't open the IDE, and I always mess up generics without the IDE
Another possible solution is to use AOP. Although I don't know the current fashion, what you describe may be a cross domain problem
The final alternative may be to use a language that allows extensions, features, protocols, or other types of "hybrid"