5

I understand if a class overrides a default method, you can access the default method in the following manner

interface IFoo {
    default void bar() {}
}

class MyClass implements IFoo {
    void bar() {}
    void ifoobar() {
        IFoo.super.bar();
    }
}

But what about the case where an interface overrides a default method? Is the parent method available in any way?

interface IFoo {
    default void bar() {}
}

interface ISubFoo extends IFoo {
    // is IFoo.bar available anywhere in here?
    default void bar {}
} 

class MyClass implements ISubFoo {
    // is IFoo.bar available anywhere in here too?

    public static void main(String[] args) {
        MyClass mc = new MyClass();
        mc.bar(); // calls ISubFoo.bar
    }
}

The verbiage Java uses for default methods is similar to that for classes, otherwise it's confusing/misleading. Subinterfaces "inherit" default methods, and can "overwrite" them. So it seems IFoo.bar should be accessible somewhere.

1
  • 1
    No, there is no super.super in Java. You can never access a method that was overridden in the parent, regardless of wether it's a class or a default method on an interface. Commented Oct 8, 2014 at 15:05

1 Answer 1

2

You can go one level up, so the IFoo.bar() is available in ISubFoo with IFoo.super.bar().

interface IFoo {
    default void bar() {}
}

interface ISubFoo extends IFoo {
    // is IFoo.bar available anywhere in here?
    // Yes it is
    default void bar {
        IFoo.super.bar()
    }
} 

class MyClass implements ISubFoo {
    // is IFoo.bar available anywhere in here too?
    // Not it is not

    public static void main(String[] args) {
        MyClass mc = new MyClass();
        mc.bar(); // calls ISubFoo.bar
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.