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
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.)
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.
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.
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 {
...
}
They are functionally equal, but the first one is preferred because it's shorter and isn't weird.