2

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();
}
}
niks
  • 1,063
  • 2
  • 9
  • 18

2 Answers2

2

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

Sleiman Jneidi
  • 22,907
  • 14
  • 56
  • 77
1

You could have a method that calls super() from CBD and call that method from EDC using super(), i.e. chain the calls.

Dave
  • 321
  • 1
  • 8