Abstract classes and methods in Java, Inheritance

后端 未结 5 885
星月不相逢
星月不相逢 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 15:56

    In Java, the abstract class annotation indicates that the class cannot be directly instantiated. A class could be declared abstract simply because it should never be instantiated (perhaps it contains only static methods), or because its subclasses should be instantiated instead.

    It is not a requirement that abstract classes contain abstract methods (the inverse is true: a class containing one or more abstract methods must be abstract.)

    The question of whether you should duplicate the abstract method definition might be perceived as a style question - but I would be hard pressed to come up with an argument in favor of duplicating the definition (the only argument I can come up with is in the case where the class hierarchy might change the semantics or use of the method, and thus you'd like to provide an additional javadoc in class B.)

    The primary argument against re-definition of the abstract method is that duplicate code is bad - it makes refactoring more cumbersome and such (all the classic "don't duplicate code" arguments apply.)

    0 讨论(0)
  • 2021-02-14 15:58

    Go with #1. Rewriting the method declaration in the child class is confusing. And you actually don't need any abstract methods in an abstract class, regardless of whether the parent is abstract or not.

    0 讨论(0)
  • 2021-02-14 16:00

    So, the question is: Which is preferred when sub classing an abstract class in java and don't want to provide implementation?

    a) mark subclass as abstract too

    b) mark subclass as abstract too AND re-write the method signature marked as abstract?

    I would go for the first one:

    a) Mark subclass as abstract too.

    The former has already the abstract method declaration, there is no point in repeating it.

    0 讨论(0)
  • 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 {
      ...
    }
    
    0 讨论(0)
  • 2021-02-14 16:14

    They are functionally equal, but the first one is preferred because it's shorter and isn't weird.

    0 讨论(0)
提交回复
热议问题