简体   繁体   中英

same method signature in interface and class

interface TestInterface {
    void work();
}

class TestClass {
    public void work(){
        System.out.println("Work in CLASS");
    }
}

public class Driver extends TestClass implements TestInterface {
    public static void main(String[] args) {
        new TestClass().work();
    }
}

Can any one explain to me, why just because the same work method signature exists in TestClass this class compiles fine?

The requirement of implementing an interface is that the class provides implementations of all the methods specified by the interface. Class Driver provides the required implementation of work() , because it inherits an exactly matching method from TestClass . So it can be used as an implementation of TestInterface .

It's because all of interface's methods are implemented. It's the same reason you can omit @Override annotation in your implementation class (not a good practice as a method signature could be changed and you can come into position where you are unintentionally implementing changed method with some other of your public methods).

However, your construct is shaky because you are depending on TestClass which is not aware of the interface you're signing to implement

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM