Search code examples
javasubclassparentsuper

Java:Convention / practice for calling parent class methods


For following code :

`

Class A
{
method1();
method2();
}

Class B extends A
{
method1();
method3();
}`

In Class B, method3 implementation is as follows:

method3()
{ 
this.method1(); // For calling method1 in class B
super.method1(); // For calling method1 in parent class A

// Following statements call method 2 in parent class
method2();      // 1 doesn't seem to be right practice
this.method2;   // 2 is more readable in case method2 is overridden in this class
super.method2();// 3 improves readability IMO
}

Which of the 3 is recommended way to call method2?


Solution

  • TL;DR:

    Using this. to call methods is useless. Using super. to call methods is required to avoid infinite recursion.

    For calling methods, both this.foo() and foo() do the same thing: call the most derived version of a given method. (For accessing member variables, things are different). There is no way in Java AFAIK to call "this class' version of a method".

    super is usually used in the context of overriding methods, to invoke base class' implementation of the method. If you omit super. you end up with method calling itself and potentially with infinite recursion. If you use super.method() in any other context, you've probably messed up your class hierarchy.