Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

java - Implementing multiple interfaces having same method

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();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()

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

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.

You can also find more information here: JLS §8.4.8.4


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...