Abstract classes and methods in Java, Inheritance

后端 未结 5 884
星月不相逢
星月不相逢 2021-02-14 15:22

I have class B, which inherits from class A. The superclass A is abstract, containing one abstract method. I don\'t want to implement the abstract method in class B, therefore I

5条回答
  •  北海茫月
    2021-02-14 16:11

    You are right, the two cases are equivalent. Case 1) is more simple, case 2) is code duplication - avoid it. But there may be one reason to do so:

    If the method in class A does not return String but lets say C, class B may override it (since Java 5) with a more specific return type, lets say D (class extends C):

    public abstract class A {
      public abstract C giveSum();
    }
    
    public abstract class B extends A {
      public abstract D giveSum();
    }
    
    public class C {
      ...
    }
    
    public class D extends C {
      ...
    }
    

提交回复
热议问题