我正在创建一个界面,说“汽车”
public interface Car {
public void drive(int Speed, int Gear ); // for cars which have gears
public void drive(int Speed); // for cars which do not have gears
}
现在我正在创建我的实现类,例如SimpleCar和AdvanceCar,其中
SimpleCar没有齿轮
AdvanceCar有齿轮
现在,当我编写实现类时,即使我不想在实现类中使用它们,也必须为这两种方法编写代码
public class SimpleCar implements Car {
public void drive(int Speed, int Gear ){ ... }; // dont want this method in SimpleCar
public void drive(int Speed ){ ... };
}
有人可以帮助我设计具有方法但实现类具有不同签名的接口吗?
最佳答案
public interface Car {
public void drive(int Speed, int Gear); // for cars which have gears
public void drive(int Speed); // for cars which do not have gears
}
public class CarAdapter implements Car {
@Override
public void drive(int Speed, int Gear) {
// TODO Auto-generated method stub
}
@Override
public void drive(int Speed) {
// TODO Auto-generated method stub
}
}
public class AdvancedCar extends CarAdapter {
@Override
public void drive(int Speed) {
// TODO Auto-generated method stub
super.drive(Speed);
}
@Override
public void drive(int Speed, int Gear) {
// TODO Auto-generated method stub
super.drive(Speed, Gear);
}
}
public class SimpleCar extends CarAdapter {
@Override
public void drive(int Speed) {
// TODO Auto-generated method stub
super.drive(Speed);
}
}