Sim*_*ley 2 java inheritance interface abstract
对不起标题,无法想出更清楚的东西.我有以下结构:
public interface Vehicle {...}
public class Car implements Vehicle {...}
Run Code Online (Sandbox Code Playgroud)
然后:
public abstract class Fixer {
...
abstract void fix(Vehicle vehicle);
...
}
Run Code Online (Sandbox Code Playgroud)
并希望:
public class CarFixer extends Fixer {
void fix(Car car) {...}
}
Run Code Online (Sandbox Code Playgroud)
但这不起作用.Eclipse说:The type CarFixer must implement the inherited abstract method Fixer.fix(Vehicle)
.知道怎么解决这个问题?
你可以使用泛型来解决这个问题:
public abstract class Fixer<T extends Vehicle> {
abstract void fix(T vehicle);
}
public class CarFixer extends Fixer<Car> {
void fix(Car car) {...}
}
Run Code Online (Sandbox Code Playgroud)
您的原始版本的问题是该fix
方法允许任何类型的车辆,但您的实施类仅允许汽车.考虑以下代码:
Fixer fixer = new CarFixer();
fixer.fix(new Bike()); // <-- boom, `ClassCastException`, Bike is a vehicle but not a car
Run Code Online (Sandbox Code Playgroud)