Java中接口的重要性 [英] The importance of interfaces in Java

查看:90
本文介绍了Java中接口的重要性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有两个班级, Tiger Airplane
这两种类型的一个共同点是Speed。我知道创建一个超类 ClassWithSpeed 然后派生子类飞机是不合逻辑的老虎来自它。
相反,最好创建一个包含方法 speed()的接口,然后在 Airplane Tiger 。我明白了。但是,如果没有接口,我们可以做同样的事情。我们可以在 Airplane 和方法 speed() speed() $ c> in Tiger
我们无法到达 Tiger 飞机的对象<唯一(可能非常大)的缺陷通过接口引用。

Let's say we have two classes, Tiger and Aeroplane. One thing in common for these two types is the Speed. I know that it would be illogical to create a superclass ClassWithSpeed and then derive subclasses Aeroplane and Tiger from it. Instead, it is better to create an interface that contains the method speed() and then implement it in Aeroplane and Tiger. I get that. But, we can do the same thing without interfaces. We could define method speed() in Aeroplane and method speed() in Tiger. The only (maybe very big) flaw it would be that we couldn't "reach" the objects of Tiger and Aeroplane through an interface reference.

我是Java和OOP的初学者,如果有人向我解释接口的作用,我将非常感激。
干杯!

I am beginner in Java and OOP, and I would be very grateful if someone explained to me the role of interfaces. Cheers!

推荐答案

这是:

public int howFast(Airplane airplane) {
    return airplane.speed();
}

public int howFast(Tiger tiger) {
    return tiger.speed();
}

public int howFast(Rocket rocket) {
    return rocket.speed();
}

public int howFast(ThingThatHasntBeenInventedYet thingx) {
    // wait... what? HOW IS THIS POSSIBLE?!
    return thingx.speed();
}

...

vs

public int howFast(Mover mover) {
    return mover.speed();
}

现在,想象一下必须返回并更改所有 howFast 将来的功能。

Now, imagine having to go back and change all those howFast functions in the future.

接口或否,每个类都必须实现或继承 speed()方法。界面允许您更轻松地使用这些不同的类,因为它们每个都承诺以某种方式运行。你将调用 speed(),他们将返回 int ,所以你不必写每个可能的类都有单独的方法。

Interface or no, each class will have to implement or inherit the speed() method. An interface lets you use those disparate classes more easily, because they've each promised to behave in a certain way. You'll call speed(), and they'll return an int, so you don't have to write separate methods for every possible class.

当您发现由于相对论物理学的突破而需要以不同方式处理速度时,您只需要更新调用 speed()的方法。当你的曾孙女为 HyperIntelligentMonkeyFish 编写课程时,她不必反汇编你的古代二进制文件并进行更改,以便你的代码可以监视和控制她的突变军队。她只需声明 HyperIntelligentMonkeyFish实现Mover

When you find you need to handle speed differently because of a breakthrough in relativistic physics, you only need to update the methods that call speed(). When your great-granddaughter writes a class for HyperIntelligentMonkeyFish, she doesn't have to disassemble your ancient binary and make changes so that your code can monitor and control her mutant army. She needs only declare that HyperIntelligentMonkeyFish implements Mover.

这篇关于Java中接口的重要性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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