0

Consider the following code:

interface IParent {
    default void print() {
        System.out.println("Interface");
    }
}

class Parent {
    public void print() {
        System.out.println("Class");
    }
}

class Child extends Parent implements IParent {
    public static void main(String []args) {
        Child c = new Child();
        c.print(); //prints Class
    }
}

Why does calling the print() method output Class?

I know for sure that if Parent was interface instead of class declared the print() method as default, then compiler error would be generated due to duplicate print() methods being inherited by the Child class.

But why does this work and why is it that Parent's method is called and not IParent's?

  • 3
    Why do you expect it to be? An interface `default` method is just that, a default implementation if a class doesn't implement it itself. `Parent` does, `Child` inherits it. – daniu Mar 26 '20 at 10:24
  • See https://stackoverflow.com/questions/32471220/super-class-method-and-interface-default-method-conflict-resolution – Hovercraft Full Of Eels Mar 26 '20 at 10:25
  • 1
    Also check out [this useful search strategy for similar questions](https://www.google.com/search?q=java+interface+default+method+conflicts+with+inherited+method+site:stackoverflow.com) – Hovercraft Full Of Eels Mar 26 '20 at 10:26
  • @daniu Please correct me if I'm mistaken, so what you mean is at runtime, print() from IParent is overriden by print() from Parent which are both inherited by Child class and thus it is invoked? – Rishabh Jain Mar 26 '20 at 10:30
  • 1
    Please read the duplicate questions and answers as your answers may be found there – Hovercraft Full Of Eels Mar 26 '20 at 10:45

0 Answers0