Search code examples
javaclasssuperclass

Calling method of Superclass from subclasses


I have faced a question in an interview whether we can access the method display() of class ABC from EDC as given below

class ABC {
    public void display() {
       System.out.println("from ABC");
    }
}

class CBD extends ABC {
    public void display() {
       System.out.println("From CBD");
    }
}

class EDC extends CBD {
    public void display() {
        System.out.println("From EDC");
    }
}

I would like to know if we can access the method of ABC from class EDC other than an object creation of ABC. I know the answer is very straight and simple that we can access only the super class method of EDC i.e; display() of CBD through super.display(), but I am feeling whether I am missing any approach here to access the display() of ABC from EDC.

I think one of the possible approaches is as below

    class ABC {
public void display()
{
   System.out.println("from ABC");
}
public static  void main(String args[])
{
      ABC obj=new EDC();
      obj.display();

}
}
class CBD extends ABC {
public void display()
{
   super.display();
}
}
class EDC extends CBD {
public void display()
{
    super.display();
}
}

Solution

  • No, it is not possible. You can only go one level up with super.