Given classes A, B, and C where B extends A and C extends B and where all classes implement the instance method void doIt(). Is it possible for the version of the doIt() method in class A to be called by an instance of class B? What is the syntax?

 




With questions like these, it helps to mentally draw out the hierarchy of classes to make it easier to visualize which class extends which. The hierarchy is basically in alphabetical order – with A on top, then B, and then C. That’s easy enough to imagine.

It turns out that what the questions asks is not possible with an instance of B. Because B overrides the doIt() method, calling the A class’s version of the doit() method is not possible with an instance of B.

However, this is possible within the definition of one of the methods of B using a call to super. The syntax for this would be super.doIt()

Hiring? Job Hunting? Post a JOB or your RESUME on our JOB BOARD >>

Subscribe to our newsletter for more free interview questions.

  • Sachin

    This is not possible.Which java version are you using.

  • Override Class inheriting the method from its super class has the option to override it. Benefit of overriding is the ability to define behaviour specific to particular class. Method…
    for more visit here http://thatsjavainfo.com/java/override/

  • cardman

    For all non static methods belonging to the class C, it is possible to call a method which is defined in a super class

    I hope this following example will help the people who will need to it.

    public class A{

    public void doIt() {

    System.out.println(“Class A”);

    }

    }

    public class B extends A{

    public void doIt() {

    System.out.println(“Class B”);

    }

    }

    public class C extends B{

    public void doIt() {

    System.out.println(“Class C”);

    }

    public void method() {

    ((A)super).doIt();//prints Class A

    }
    }