Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java inheritance; passing a subclass to an abstract method of a superclass

Sorry for the title, couldn't come up with anything clearer. I have the following structure:

public interface Vehicle {...}
public class Car implements Vehicle {...}

then:

public abstract class Fixer {
...
   abstract void fix(Vehicle vehicle);
...
}

and would like to have:

public class CarFixer extends Fixer {
    void fix(Car car) {...}
}

but this doesn't work. Eclipse says: The type CarFixer must implement the inherited abstract method Fixer.fix(Vehicle). Any idea how can I solve this?

like image 730
Simon Righley Avatar asked Jan 28 '26 22:01

Simon Righley


1 Answers

You can use Generics to solve this:

public abstract class Fixer<T extends Vehicle> {
    abstract void fix(T vehicle);
}

public class CarFixer extends Fixer<Car> {
    void fix(Car car) {...}
}

The problem with your original version is that the fix method allows any type of vehicle, but your implementing class allows only cars. Consider this code:

Fixer fixer = new CarFixer();
fixer.fix(new Bike()); // <-- boom, `ClassCastException`, Bike is a vehicle but not a car
like image 53
Absurd-Mind Avatar answered Jan 31 '26 13:01

Absurd-Mind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!