Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Is it possible to extend all the subclasses of a class with a single class?

Java - Is it possible to extend all the subclasses of a class with a single class?

Let's explain it with an example, the actual code is quite more complex. I have an Animal class with its own class hierarchy. Let's say that 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 the Car subclasses with a 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 of a specific subclass. Something like

RegisteredCar c = new RegisteredCar<Viper>("B-3956-AC");

And call the c.getManufacturer() to obtain "Dodge" and c.getPlateNumber() to obtain B-3956-AC. Obviously, I should still be able to create a Car c = new Viper();

That is an example. Having an attribute in Car with null value if not registered is not enough for what I need.

like image 218
Francesc Lordan Avatar asked Feb 20 '16 12:02

Francesc Lordan


People also ask

How many subclasses can create from a single class?

A class can have more than one class derived from it. So we have one base or superclass and more than one subclasses. This type of inheritance is called “Hierarchical inheritance”.

Can a class extend more than 1 class in Java?

A class can extend only one class, but implement many interfaces. An interface can extend another interface, in a similar way as a class can extend another class.

Can a class have multiple subclasses in Java?

A Java class can have only one direct superclass. Java does not support multiple inheritance.

Can a class have more than one subclass?

Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass.


1 Answers

In short, no that is not possible. You have to unfortunately modify your object model.

For example, what about having a Registration class this way:

public interface Registration<C extends Car> {
    C getCar();

    String getPlateNumber();
}

This way you can extract the information relating to registration in a single class, while maintaining your Car models.

You can then do helper methods like:

Registration<Viper> registeredViper = createRegistration(new Viper(), "B-3956-AC");
like image 102
Robert Bräutigam Avatar answered Nov 14 '22 20:11

Robert Bräutigam