为什么要声明一个接口然后在Java中用它实例化一个对象? [英] Why would you declare an Interface and then instantiate an object with it in Java?

查看:458
本文介绍了为什么要声明一个接口然后在Java中用它实例化一个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我和朋友正在学习Java。我们今天正在研究接口,我们讨论了如何使用接口。

A friend and I are studying Java. We were looking at interfaces today and we got into a bit of an discussion about how interfaces are used.

我朋友给我看的示例代码包含:

The example code my friend showed me contained this:

IVehicle modeOfTransport1 = new Car();
IVehicle modeOfTransport2 = new Bike();

其中 IVehicle 是一个在汽车和自行车类中实现的界面。
定义接受 IVehicle 作为参数的方法时,可以使用接口方法,当运行代码时,上述对象正常工作。然而,当你通常想要这样宣布汽车和自行车时,这种方法非常好:

Where IVehicle is an interface that's implemented in both the car and bike classes. When defining a method that accepts IVehicle as a parameter you can use the interface methods, and when you run the code the above objects work as normal. However, this works perfectly fine when declaring the car and bike as you normally would like this:

Car modeOfTransport1 = new Car();
Bike modeOfTransport2 = new Bike();

所以,我的问题是 - 为什么在声明和实例化时,为了对后者使用前一种方法? modeOfTransport 对象?这有关系吗?

So, my question is - why would you use the former method over the latter when declaring and instantiating the modeOfTransport objects? Does it matter?

推荐答案

那里没关系。

真正重要的是需要在IVehicle上运行的其他接口。如果他们接受参数并将值返回为IVehicle,则代码将更容易扩展。

Where it really matters is in other interfaces that need to operate on IVehicle. If they accept parameters and return values as IVehicle, then the code will be more easily extendible.

如您所述,这些对象中的任何一个都可以传递给接受的方法IVehicle作为参数。

As you noted, either of these objects can be passed to a method that accepts IVehicle as a parameter.

如果您有后续代码使用了Car或Bike特定的操作,那么将它们声明为Car或Bike将是有利的。 Car and Bike特定操作可用于每个相关对象,并且两者都可以作为IVehicle使用(即可以传递)。

If you had subsequent code that used Car or Bike specific operations that were used, then it would be advantageous to declare them as Car or Bike. The Car and Bike specific operations would be available for each of the relevant objects, and both would be usable (i.e. could be passed) as IVehicle.

这篇关于为什么要声明一个接口然后在Java中用它实例化一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆