开发者

Java - extending a class and reusing the methods?

开发者 https://www.devze.com 2023-03-14 21:24 出处:网络
public class BaseClass { public void start() { // do something } } public class ClassA extends BaseClass {
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();
   }
}


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.


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.


public class ClassA extends BaseClass {
  @Override
  public void start() {
     super.start();
  }
}

does exactly the same thing as not overriding at all like this

public class ClassA extends BaseClass {}

So unless you have some extra functionality to add (in which case you call super class's method and then add your extra logic) or to do something different(you don't call super class's method and just define some different logic), it's best you don't override super class's method (and call super class's method) because it's pointless.


I sometimes do this (temporarily, during development) when I want to set a break-point there.


The main reason behind the concept of inheritance is generalization of the functions or operations that are common among sub classes. It makes sense to override only when we need to customize the operation for the particular sub-class.

  • But one place where we do need to make an override is, say you have overloaded your super class default constructor, then in sub-class you need to mention the invocation of the overloaded super-class constructor as the first line in your sub-class constructor(ie Super-class object has to be created before sub-class creation). For example

class BaseClass{

Baseclass(arg1){

}

}

class A extends BaseClass{

A{ super(arg1); }

}

In other places it would only add a redundancy of the code, which is not at all necessary

0

精彩评论

暂无评论...
验证码 换一张
取 消