Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - extending a class and reusing the methods?

public class BaseClass {
   public void start() {
      // do something
   }
}

public class ClassA extends BaseClass {

}

ClassA c = new ClassA();
c.start();

In the following code I want to use the start() method as it was defined in the super class, I have seen in a lot of other developer's codes that they override the method in the super class and then they call the super. is there a reason for that?

public class ClassA extends BaseClass {
   @Override
   public void start() {
      super.start();
   }
}
like image 526
aryaxt Avatar asked Jun 24 '11 01:06

aryaxt


2 Answers

Clarity? Some developers feel it is clearer to show the method in the subclass. I disagree. It's redundant info.

At least since Java 5, you could add an @Override so the compiler will tell you if the signature changes/disappears.

Except for constructors. For constructors, you really do have to create your own with the same signature and delegate upwards. In this case, omitting isn't equivalent though.

like image 167
Jeanne Boyarsky Avatar answered Oct 30 '22 12:10

Jeanne Boyarsky


Overriding a method, doing something special, then calling super.method() is called decorating a method - you're adding to the behaviour. Read more here: Decorator Pattern.

Overriding it without calling super's method is simply overriding a method - changing the behaviour.

like image 34
Bohemian Avatar answered Oct 30 '22 13:10

Bohemian