Why use an abstract class without abstract methods?
I am now studying a java and I'm at the part of Abstract. I read sorta strange part to me that there is an abstract class which does not include any abstarct method.
Why do they use this kind of class?
Solution 1:
To prevent instantiation of that class and use it only as a base class. Child classes can use the general methods defined in the abstract class.
For example it doesn't make sense to create an instance of AbstractVehicle
. But All vehicles can reuse a common registerMileage(int)
method.
Solution 2:
A common reason to do this is to have the abstract
class provide exploding implementations of the abstract
methods as a convenience to subclasses who don't have to implement all the abstract
methods, just those they want to - the remaining ones will still explode but it won't matter if those execution paths aren't exercised.
HttpServlet is an example of this pattern in action. It has default implementations for all methods that handle the different request types, but they all throw an exception. The subclass must override these if they want to do something meaningful. It's OK to leave some handler methods not overridden as long as they are never called.