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

查看:29
本文介绍了为什么要声明一个接口,然后在 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 和 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天全站免登陆