6

I was reading Java SCJP book by Khalid A. Mughal (for JE6), and in topic 7.6 Interfaces and Page number 313, it is given that

A subinterface can override abstract method declarations from its superinterfaces. Overridden methods are not inherited.

I could not quite understand what "Overridden methods are not inherited." means. I tried to do this:

interface A
{
    void abc();
}

interface B extends A
{
    @Override
    void abc();
}

interface C extends B
{
    void abc();
}

And I did not get any error. What am I not understanding?

8
  • Overriding methods does not apply to interfaces, only classes. Aug 2, 2015 at 17:41
  • But in book it is said in context of interfaces Aug 2, 2015 at 17:42
  • In Java 8, interfaces can have default implementations to methods but in earlier versions the concept of overriding doesn't make sense wrt interfaces. Aug 2, 2015 at 17:47
  • 1
    @MickMnemonic You can override an abstract method declaration by another abstract method declaration. This can involve making the return type more restrictive or changing the list of exceptions thrown. Aug 2, 2015 at 17:52
  • 3
    Return types are not part of method signature Aug 2, 2015 at 17:57

1 Answer 1

2

This simply means that overridden methods can have a slightly different signature than the superinterface's methods. For example:

public interface Foo {
    Object doSomething(String input) throws IOException;
}

public interface Bar extends Foo {
    @Override
    String doSomething(String input);
}

As you can see, in the subinterface, I no longer throw a checked exception, and I guarantee that the returned object is a more specific type. The method that did throw a checked exception is not inherited, because it is overridden.


I don't have the context of the entire paragraph, but there's something else related that applies only to implementations and not interfaces, which is that if you override a method without explicitly calling super, the superclass's implementation won't occur.

For example, if I have:

public class Example {
  public static class Foo {
    public void printSomething() {
      System.out.println("Foo");
    }
  }

  public static class Bar extends Foo {
    @Override
    public void printSomething() {
      System.out.println("Bar");
    }
  }

  public static void main(String[] args) {
    Bar bar = new Bar();
    bar.printSomething();
  }
}

This program will simply output:

Bar

but NOT Foo. If I add a call to super.printSomething(), then it will print both.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.