Search code examples
javaoopinheritancepolymorphismabstract-class

How to call a method of super class from parent class. How to call the same method from interface?


I am learning java and I am trying to recreate a scenario where A class is extending an abstract class and also implementing an interface. Each abstract class and interface have a same method defined in them. Now from the class which is extending and implementing, I want to call the implementations of both the parents. I tried to recreate this scenario as below but it gave me the error: not an enclosing class: A

interface C {
  default void m1(){
      System.out.println("C");
  }
}

abstract class A{
  abstract void display();
  void m1(){
      System.out.println("A");
  }
}

class B extends A implements C{
    public void m1(){
    }
    void display() {
        C.super.m1();
        A.super.m1(); // error: not an enclosing class: A
    }
}

public class Main {
  public static void main(String[] args) {
    A obj = new B();
    obj.display();
  }
}

Solution

  • You don't need to explicitly name a superclass to invoke its methods, because a Java class can only extend one superclass, so MyClass.super.method() is unambiguous. In fact, you needn't even name the child class at all: super.method() is also unambiguous due to Java's single inheritance model.

    You do need to explicitly name a super-interface to invoke its methods, because a Java class can implement multiple interfaces, so MyInterface.super.method() is necessary to identify which interface is being invoked.

    interface MyInterface {
        default void m1(){
            System.out.println("MyInterface");
        }
    }
    
    abstract class MyAbstractClass {
        public void m1(){
            System.out.println("MyAbstractClass");
        }
    }
    
    public class MyClass extends MyAbstractClass implements MyInterface {
        @Override
        public void m1() {
            super.m1();             // MyAbstractClass
            MyClass.super.m1();     // MyAbstractClass
            MyInterface.super.m1(); // MyInterface
        }
    
        public static void main(String... args) {
            new MyClass().m1();
        }
    }