0

I have an interface A with a default method printme(), same method I am having in an abstract class B. If I am extending abstract class B with a TestClass and implementing interface A, printme() method is not visible in TestClass. Below is code:

interface A {

    default void printme() {
        System.out.println("Interface A");
    }
}

abstract class B {
    public void printme() {
        System.out.println("Abstract Class B");
    }
}

public class TestDefaultMethod extends B implements A {

    public static void main(String[] args) {
        TestDefaultMethod td = new TestDefaultMethod();
        td.printme(); //from Interface A
    }
}

I am not able to understand how and why I am not able to access method from Abstract class.

Holger
  • 285,553
  • 42
  • 434
  • 765
Vivek Panday
  • 1,426
  • 2
  • 16
  • 34
  • 1
    In what sense aren't you able to access the method from the abstract class? (It's the interface method I wouldn't expect you to be able to access.) – Louis Wasserman Jul 19 '16 at 05:34
  • 1
    I ran this code and got "Abstract Class B". – Eran Jul 19 '16 at 05:36
  • See, If you do "td.printme()" the printme() method is visible from Interface A , but I am unable to understand why I can not access method "printme()" which is given in Abstract class B – Vivek Panday Jul 19 '16 at 05:36
  • @Eran , thats correct at run time you td.printme() is executing method from Abrstact class but at Compile time its picking method from interface A. If you are using any editor like eclipse , you can do td.pri... and in help suggestion given by eclipse , you see printme() method is from interface A. – Vivek Panday Jul 19 '16 at 05:40
  • 2
    And if you hit F2 on the method call in Eclipse, you'll see `void B.printme()`. So your problem is not "compile time", but Eclipse auto-completion, which has *nothing* to do with compile-time. It seems that auto-completion eliminated the wrong "duplicate" of the method. File a bug with Eclipse. – Andreas Jul 19 '16 at 05:43
  • Are you using NetBeans? This works fine for me in Eclipse. I've seen several problems recently regarding NetBeans' compiler having trouble with overloading resolution. – Jim Garrison Jul 19 '16 at 05:48
  • @Andreas You are correct .now I am confused ,why not default method given in interface A is being called ,Please explain how its working – Vivek Panday Jul 19 '16 at 05:48
  • The default would be used only if there was no other implementation further down the inheritance tree (below A). Since `B#printme()` exists, it is used. – Jim Garrison Jul 19 '16 at 05:50
  • @Andreas: thanks for hinting to the Eclipse issue. – Holger Jul 19 '16 at 08:27

0 Answers0