0

Say you have a TeachingAssistant who extends Student who extends Person.

If both Student and Person have a method x() and I have an instance of TeachingAssistant, how do I differentiate between calling Student's x() method and Person's x() method?

Is super.super.x() a valid call?

Alexis C.
  • 91,686
  • 21
  • 171
  • 177
xheyhenry
  • 1,049
  • 2
  • 13
  • 25
  • If you really need `super.super`, I'd say you have a design problem. You probably have too much going on in one class hierarchy, and some of the functionality needs to go out into separate classes. Composition may be a better pattern than inheritance for your situation. – jpmc26 Dec 10 '13 at 09:05
  • yeah, some code would go a long towards clarifying what's being asked. – Thufir Dec 11 '13 at 08:59

2 Answers2

0

There are many, many bad ideas in the following code:

package supersuper;

import static java.lang.System.out;

interface Human {

    String x();
}

class Person implements Human {

    public String designation;  //bad idea

    Person() {
        designation = x();
    }

    @Override
    public String x() {
        return "Person";
    }
}

class Student extends Person {

    Student() {
        super();
    }

    @Override
    public String x() {
        return "Student";
    }
}

class TeachingAssistant extends Student {

    TeachingAssistant() {
        super();
    }
}

public class SuperSuper {

    public static void main(String[] args) {
        TeachingAssistant ta = new TeachingAssistant();
        out.println(ta.designation);
    }
}

dunno what you want, really. Post some code as a starting point for some context. But, no, you cannot invoke super.super.x() as per the comments.

I only present this to you get you started to refine your question.

Thufir
  • 8,216
  • 28
  • 125
  • 273
0

First rethink whether your class hierarchy really matches the problem domain. If you still need to specifically call the grandparents implementation of a method overridden in the parent you have 2 choices:

First choice. Add an alias method in the grandparent.

class grandPa {
   int foo() {
      return myfoo;
   }
   // Alias method 
   int grandPaFoo() {
      return foo();
   }
}
class Pa extends grandPa {
   int foo() {
      return bar;
   }
}

class Child extends Pa {
   int foo() {
   if (x>3) {
      // User parent implementation
      super.foo();
   } else {
      // User grandparent implementation via alias
      grandPaFoo();
   }
}

Second choice. Use composition instead of inheritance.

Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82