1

What's the proper convention to access ancestor and parent methods from down an inheritance chain?

For example, methodA() resides in the base ancestor class and methodB() resides in the parent class. If I'm in a child/subclass that extends parent (which in turn extended the ancestor/base class), what is the proper way to access methodA()?

Obviously super.super.methodA() is not allowed.

What does work is super.methodA(), this.methodA() and simply calling methodA() on it's own.

Which of the above three cases is the 'correct' way to call methodA() that resides in the ancestor class?

Brownbay
  • 5,400
  • 3
  • 25
  • 30

2 Answers2

2

If methodA() is defined only in the grandparent class, and isn't overridden in the parent class or child class, then simply calling methodA() in the child class will correctly call the inherited method.

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • I guess the what I really wanted to get at is the ambiguity in the various forms of method calls. To an external programer (especially in no API/docs are available), how does one know where methodA() resides. super.xxx would imply a parent call. this.xxx would imply a resident call and so would simply xxxx() – Brownbay Mar 08 '11 at 22:28
  • 1
    @Chrys: there is no ambiguity. A method call will resolve to the method on the most-specific type. If you don't provide a meaningful API or documentation, then users of your code would have to figure it out the same way that the author of the library (you) would: walk the inheritance hierarchy to find the closest class the method is defined in. – Matt Ball Mar 08 '11 at 22:31
1

Accessing a classes grandparent methods is not allowed. See Why is super.super.method(); not allowed in Java? form more information.

Community
  • 1
  • 1
Richard Miskin
  • 1,260
  • 7
  • 12
  • I guess my question was a bit ambiguous. I am able to access methodA() using any of the there method calls in my question above. Since the parent class extends the grandparent, any class that extends the parent would also have access to the grandparents methods as they flow down the inheritance chain. – Brownbay Mar 08 '11 at 22:25