Java How to call method of grand parents?

20,960

Solution 1

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".

Solution 2

You can't, and you shouldn't.

This is a sign of bad design. Either rename a method or include the required common functionality in another method or an utility class.

Share:
20,960

Related videos on Youtube

Arkaha
Author by

Arkaha

Updated on July 09, 2022

Comments

  • Arkaha
    Arkaha almost 2 years

    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(); ??
      }
    }
    
    • Macarse
      Macarse about 14 years
      Why would you do that? Can you give an example?
  • Joachim Sauer
    Joachim Sauer about 14 years
    Reflection also doesn't provide a way to do this, the normal rules of runtime polymorphism will still apply. You can't even implement super.myMethod() using reflection, let alone the theoretical super.super.myMethod().
  • Arkaha
    Arkaha about 14 years
    Thanks guys! i will try to rework my design.
  • luis.espinal
    luis.espinal about 14 years
    Not necessarily, you need to do that when you define inner classes (for example, defining action listeners in Swing or call back classes.) Outside of such situations, yes, it is bad design, but by itself it is not. Java syntax supports it anyhow (see my response to Arkaha's question.)
  • luis.espinal
    luis.espinal about 14 years
    Arkaha, see my answer to your question. It is syntactically possible to call a method defined by a superclass that it is not your immediate ancestor (your super). But you need to have a valid reason for doing so.