same method signature in interface and class

265 views Asked by At
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?

2

There are 2 answers

0
khelwood On

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.

0
5ar On

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