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();
}
}
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 inclass Testdoesn’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.