我有这个问题很长时间了,但是所有回答我的人都没有给我正确的答案。我认为这些接口在 OOP 语言中用于多态性,并且在如下情况下我不明白如何处理它,[在 java 中]
让我们采用以下接口和两个类,
public interface Vehicle{
public int noOfWheels();
public String movingMethod();
}
public class Car implements Vehicle{
public int noOfWheels(){
return 4;
}
public String movingMethod(){
return "Drive";
}
}
public class Flight implements Vehicle{
public int noOfWheels(){
return 5;
}
public String movingMethod(){
return "Fly";
}
//a behaviour only applicable to a flight
public int noOfWings(){
return 5;
}
}
=======================================
simulation
Vehicle v1 = new Car();
System.out.println(v1.noOfWheels());
System.out.println(v1.movingMethod);
Vehicle v2 = new Flight();
System.out.println(v2.noOfWheels());
System.out.println(v2.movingMethod);
System.out.println(v2.noOfWings());//this is not working as Vehicle interface doesn't have this method.
那么,我们如何才能实现此类问题的解决方案。我知道我们可以为航班类型创建另一个界面,但我举了这个例子来表达我的问题。