Was*_*RAR 8 java methods implementation interface class
我有一个接口和两个正在实现接口的类.
public interface MyInterface {
public void firstMethod();
public int secondMethod();
}
public class MyClass1 implements MyInterface {
public void firstMethod() {}
}
public class MyClass2 implements MyInterface {
public void firstMethod() {}
public int secondMethod() {}
}
Run Code Online (Sandbox Code Playgroud)
这堂课MyClass1告诉我Add unimplemented methods,因为secondMethod没有实施,好的我会这样做.但问题是我不需要这种方法MyClass1.
在您看来,最好的做法是什么?
return 0Joh*_*lla 15
您应该执行以下操作之一:
将界面分解为更小的部分并根据需要进行组合.这是首选方法,尤其是在您控制的情况下MyInterface.
返回最合理的默认值.
扔一个UnsupportedOperationException.
这是一个更具说明性的例子.假设您的界面如下所示:
public interface Driveable {
public Position accelerate(Vector v, Time t);
public String getVehicleIdentificationNumber();
}
Run Code Online (Sandbox Code Playgroud)
如果您MyClass1实际上是一个Boat并且没有车辆识别号码,那么您实施此功能是没有意义的.事实上,这实际上是错误的.其他客户希望您拥有此值,但您无法将其提供给他们.
如果需要,最好使用正确的切片将接口块组合成较小的块.例如,您可能会写这样:
public interface Driveable {
public Position accelerate(Vector v, Time t);
}
public interface Vehicle extends Driveable {
public String getVehicleIdentificationNumber();
}
public class Boat implements Driveable { ... }
public class Car implements Vehicle { ... }
Run Code Online (Sandbox Code Playgroud)
这是最好的方法,因为它根据需要在接口上完全分割责任.
如果真的是你的域重要的是所有Driveables有一个车辆识别号码,而这仅仅是其中的车辆识别号码未知或不可用的特殊情况,那么你可以提供一个默认的实现:
public String getVehicleIdentificationNumber() {
return "";
}
Run Code Online (Sandbox Code Playgroud)
如果您的域中根本没有返回车辆识别号码,那么您应该抛出异常:
public String getVehicleIdentificationNumber() {
throw new UnsupportedOperationException("vehicle identification
number not supported on boats");
}
Run Code Online (Sandbox Code Playgroud)