Let’s take a glance at the following code in Java.
interface FirstInaterface
{
public void show();
}
interface SecondInterface extends FirstInaterface
{
@Override
public void show();
public void someConcreteMethod();
}
interface ThirdInterface extends SecondInterface
{
@Override
public void show();
}
final class Demo implements ThirdInterface
{
@Override
public void show()
{
System.out.println("The show() method invoked");
}
@Override
public void someConcreteMethod()
{
System.out.println("The someConcreteMethod() method invoked");
}
}
final public class Main
{
public static void main(String[] args)
{
Demo demo=new Demo();
demo.show();
demo.someConcreteMethod();
}
}
The above code in Java shows a multilevel inheritance of interfaces in which ThirdInterface has two interfaces above it. The show() method is firstly being overridden in the interface SecondInaterface ahd then again in the interface ThirdInterface and this interface is finally being inherited by the class Demo.
In such a scenario, which version of the show() methods from the above interfaces will be incorporated by the class Demo? How is the compiler able to resolve a specific version of the show() method dynamically at run time?
I feel that the show() method in the last interface in the above interface inheritance hierarchy (namely ThirdInterface) will be invoked by the compiler. If it is so then, the show() methods in the above two interfaces (namely, FirstInaterface, SecondInaterface) are useless and serve no purpose at all, since they are declared within interfaces, they themselves can never have their own implementations anywhere. When such kind of interface inheritance is useful?
Only method implementations can override, not method specifications in an interface.
What “versions”? The method signatures are identical, so there is really only one method specification. At runtime, there will be an implementation class, and only the method implementation in that class is what gets actually called.
Um, what about classes that implement
FirstInterfacedirectly? If anything, what serves no (technical) purpose is “overriding” methods in child interfaces. IfSecondInterfaceandThirdInterfacedid not have ashow()method, it would have exactly the same syntactical effect.However, there can be a valid reason to override methods in a child interface: to provide a different comment explaining semantic changes in the method contract. Examples for this can be seen in the collections framework of the Java API:
Set.add()has a different contract thanCollection.add(), since it adds the restriction that duplicate elements should not be added.