我和一个 friend 正在学习 Java。我们今天正在研究接口(interface),我们就如何使用接口(interface)进行了一些讨论。
我 friend 给我看的示例代码包含以下内容:
IVehicle modeOfTransport1 = new Car();
IVehicle modeOfTransport2 = new Bike();
IVehicle 是在汽车和自行车类中实现的接口(interface)。 当定义一个接受 IVehicle 作为参数的方法时,您可以使用接口(interface)方法,并且当您运行代码时,上述对象正常工作。但是,当您像通常这样声明汽车和自行车时,这非常有效:
Car modeOfTransport1 = new Car();
Bike modeOfTransport2 = new Bike();
所以,我的问题是 - 在声明和实例化 modeOfTransport 对象时,为什么要使用前一种方法而不是后一种方法?有关系吗?
最佳答案
使用接口(interface)声明它们有一个很大的好处,即所谓的“编码到接口(interface)”,而不是“编码到实现”是大Object Oriented Design (OOD
)原则上,这样你就可以像这样声明一个方法:
public void (IVehicle myVehicle)
这将接受任何实现该接口(interface)的对象,然后在运行时它将像这样调用实现:
public void (IVehicle myVehicle)
{
myVehicle.run() //This calls the implementation for that particular vehicle.
}
要回答最初的问题,为什么要使用其中一个,原因有几个:
1) 使用接口(interface)声明它们意味着您以后可以将该值替换为实现该接口(interface)的任何其他具体类,而不是被锁定在该特定具体类中
2) 您可以通过使用接口(interface)声明它们来充分利用多态性,因为每个实现都可以在运行时调用正确的方法。
3)你遵循OOD原则的代码到一个接口(interface)
关于java - 为什么要声明一个接口(interface),然后在 Java 中用它实例化一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7716435/