2

My Question is like that if there is a child class extend by father class and which is extended by Grandfather class then how can child class directly access the Grandfather's method.

2 Answers2

6

This is best illustrated by an example:

public class GF {
    public void one() { ... }
    public void two() { ... }
}

public class F extends GF {
    public void two() { ... }
}

public class C extends F {
    public void one() {
        super.one(); // Calls one in GF
    }

    public void two() { 
        super.two(); // Calls two in F
    }
}

The syntax for calling an overridden method from within a subclass is super.method(....). But you can only do this to call the first level overridden method. If that method is itself an override, then you cannot call the 2nd-level override; e.g. there is NO WAY for C.two() to directly call GF.two(). You can't do it reflectively, and even the JVM bytecodes won't allow it.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
1

It depends on the grandfathers's method visibility. Generally it could be accessed just as a father's method. If you want to skip a parent's override of a grandfather method, you cannot do it without modifying the parent.

The only way to call grandfather's method would be like this:

public class GF {
    public void m() {
        //do something
    }
}

public class F {

    public void m() {
        //do something that you don't need in son
    }

    /* add this method for the clean access to GF*/
    public void gfM() {
        super.m();
    }
}

public class S {
    public void aMethod() {
        gfM(); //actually calls the GF.m() method
    }
}
tibtof
  • 7,857
  • 1
  • 32
  • 49
  • Visibility is public but when we use super class method we use super keyword but in this case what will we use so that we can access the grandfather's method directly. – Vinit Kumar Kamboj Jun 12 '12 at 09:41