实现具有相同方法的多个接口 [英] Implementing multiple interfaces having same method

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

问题描述

此代码完美无缺。方法test()适用于两个接口。引擎盖下究竟发生了什么?这个功能在实际场景中有用吗?

This code works perfectly. The method test() works for both interfaces. What is exactly going on under the hood? And how is this feature useful in practical scenario?

interface A
{
    void test();
}

interface B 
{
    void test();
}

class C implements A, B
{

    public void test() 
    {
        System.out.println("abc");
    }
}

   A a = new C();
   a.test();
   B b = new C();
   b.test();


推荐答案

因为它是一个界面,所以不会造成任何伤害。你基本上是通过实现 A B 来为你的 C 类使用蓝图code>。 A B 都说 C 应该实现一个方法叫 test()

Because it's an interface there is no harm done. You're basically using a blueprint for your C class by implementing A and B. Both A and B say that C should implement a method called test()

你的 C 类实现了方法,所以接口完成了他们的工作。

Your C class implements that method, so the interfaces have done their job.

这基本上是你的 C 类说:哦,嘿,我需要实现 test(),因为接口 A 并且你实现了它。然后你的 C 类说哦,嘿,我需要再次实现 test()因为接口 B 并且它看到已经实现了一个名为 test()的方法,因此它已经满足。

It's basically your C class saying: "Oh hey, I need to implement test() because of interface A" and you implement it. Then your C class says "Oh hey, I need to implement test() again because of interface B" and it sees that there is already a method called test() implemented so it's satisfied.

您还可以在此处找到更多信息:JLS§8.4.8.4

You can also find more information here: JLS §8.4.8.4

这篇关于实现具有相同方法的多个接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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