Omar.Nassar
Omar.Nassar

Reputation: 379

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?

Upvotes: 0

Views: 266

Answers (2)

5ar
5ar

Reputation: 84

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

Upvotes: 2

khelwood
khelwood

Reputation: 59146

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.

Upvotes: 2

Related Questions