Java How to call method of grand parents?

Arkaha picture Arkaha · Apr 6, 2010 · Viewed 19.8k times · Source

Possible Duplicate:
Why is super.super.method(); not allowed in Java?

Let's assume I have 3 classes A, B and C, each one extending the previous one.

How do I call the code in A.myMethod() from C.myMethod() if B also implements myMethod?

class A
{
  public void myMethod()
  {
    // some stuff for A
  }
}

class B extends A
{
  public void myMethod()
  {
    // some stuff for B
    //and than calling A stuff
    super.myMethod();
  }
}

class C extends B
{
  public void myMethod()
  {
    // some stuff for C
    // i don't need stuff from b, but i need call stuff from A
    // something like: super.super.myMethod(); ?? how to call A.myMethod(); ??
  }
}

Answer

Tom Hawtin - tackline picture Tom Hawtin - tackline · Apr 6, 2010

You can't. This is deliberate.

Class B provides an interface (as in the concept, not the Java keyword) to subclasses. It has elected not to give direct access to the functionality of A.myMethod. If you require B to provide that functionality, then use a different method for it (different name, make it protected). However, it is probably better to "prefer composition over inheritance".