我正在创建一个界面说“汽车”
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
现在,当我编写实现类时,我被迫为这两种方法编写代码,即使我不想在实现类中使用它们
public class SimpleCar implements Car {
public void drive(int Speed, int Gear ){ ... }; // dont want this method in SimpleCar
public void drive(int Speed ){ ... };
}
有人可以帮我设计一个有方法但实现类有不同签名的界面吗?
答案 0 :(得分:3)
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);
}
}
答案 1 :(得分:2)
您应该有一个Car
接口和另一个名为GearCar
的接口,它扩展了Car
接口。
这样您就可以实现GearCar or Car
接口。
答案 2 :(得分:2)
参见以下设计。我已根据您的要求从gear
接口原因删除了Car
,因为它对所有汽车无效,因此无法成为界面的一部分。
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 abstract class SimpleCar implements Car
{
public void drive(int speed) { ... }
public abstract void accelerate(); // you can move it to interface also
}
public abstract class AdvancedCar implements Car
{
protected int CURRENT_GEAR = 1;
public void drive(int speed) { ... }
public void changeGear(int gear) { ... }
public abstract void accelerate();
}
public class Reva extends SimpleCar
{
// provide implementation for accelerate
}
public class Ferrari extends AdvancedCar
{
// provide implementation for accelerate
}
答案 3 :(得分:1)
编写一个CarAdapter
,在接口中提供所有方法的空实现。然后让您的SimpleCar
扩展CarAdapter
(默认情况下会Car
)
这在Swing应用程序中经常出现。
答案 4 :(得分:0)
只需删除需要Gear
的方法声明,因为在您的类中,您需要实现在您实现的接口中声明的每个方法,除非您的类本身是抽象的。
如果您不想实现接口的任何方法,那么您应该将SimpleCar
和AdvancedCar
作为抽象类。
答案 5 :(得分:0)
public interface Vehicle {
public void drive(int Speed);
}
public interface Car extends Vehicle{
public void drive(int Speed, int Gear );
}
public class SimpleCar implements Vehicle {
public void drive(int Speed ){ ... };
}
public class AdvancedCar implements Car {
public void drive(int Speed, int Gear ){ ... };
public void drive(int Speed ){ ... };
}