AZ_
AZ_

Reputation: 21899

Interface method shadowing Java

I am having some interesting problem with interfaces, please help me understand this concept.

I have three interfaces Itest, Itest3, Itest4. Interface Itest extends both Itest3 and Itest4 interfaces. They both interfaces have common one method public void one(); Now a class Test implements Itest interface and overrides method one()

Now of which interface it inherits method of? What if I want to inherit common method of specific interface. And What effect it has on polymorphism ? what if another class only inherits Itest3 only. I think this will break at runtime.

Please help me understand what the advantage is of that?

Code is here...

public interface ITest extends Itest4,Itest3 {
    public static interface ITest2{

    }
}

public interface Itest3 {
    public void one();
}

public interface Itest4 {
    public void one();
}

public class Test implements ITest {    

    @Override
    public void one() {
        //Which interface method it overrides?
    }

public static void main(String... arg) {
        new Test();
    }

}

Upvotes: 0

Views: 411

Answers (2)

Aluan Haddad
Aluan Haddad

Reputation: 31863

The declaration

public interface Itest3 {
    public void one();
}

Simply states that any implementer of Itest3 will provide a method that is named one, takes no arguments, and returns void.

In exactly the same way

The declaration

public interface Itest4 {
    public void one();
}

also states that any implementer of Itest4 will provide a method that is named one, takes no arguments, and returns void.

Interfaces simply exist to specify a behavioral contract, irrespective of the implementation of said behavior. Thus,

public class Test implements ITest {    

    @Override
    public void one() {
        //Defines the behavior of both interfaces
    }
}

Defines a class which implements both interfaces. This is because the method implementation satisfies the requirements of both interfaces.

Upvotes: 2

Philipp
Philipp

Reputation: 69693

The answer is: it doesn't matter.

An interface is just declarations, not code. Both interfaces declare a method public void one(). When you have an implementing class which implements this method, it implements it for both interfaces at the same time. This implementation in class Test doesn't override anything. It's the first implementation. There are no implementations in the interfaces it could override - just two identical declarations for it.

When another class implements ITest3, it will need its own implementation for public void one(). Just like any other class which implements ITest4, or ITest. The only case where you wouldn't need an own implementation, is when you would have a class which extends the class Test, because it could inherit the implementation from Test.

Upvotes: 4

Related Questions