Search code examples
javainheritanceinstancesubclasssuperclass

Using "super" keyword or using a superclass instance when calling superclass methods locally in a method from subclass?


Let say I have:

class Superclass {
  //fields...

  methodA() {...}

  methodB() {...}

...
}

class Subclass extends Superclass {
   //fields...

   methodA() {
      // Here I need to call methods A and B from superclass:
      // For this, I can use supper
      super.methodA();
      super.methodB();

      // Or I have to instantiate the superclass and use the instance
      Superclass superclass = new Superclass();
      superclass.methodA();
      superclass.methodB();
}

It works both ways, but I want to know which is better to use. Any of these ways is a bad programming technique? I hope you give me answer and arguments.


Solution

  •   super.methodA();
    
      Superclass superclass = new Superclass();
      superclass.methodA();
    

    These two calls of methodA work on different instances, so they are completely different. super.methodA() executes methodA on the current instance. superclass.methodA() executes methodA on a new instance of Superclass which is not related to the current instance.

    You would almost always use the first option. As for the second option, It doesn't make sense to create a new instance, call a method on that instance and then never do anything with that instance again.