views:

191

answers:

4

Hi I have a doubt regarding HttpServlet class is an abstract class even though there is not any abstract method in the class , all methods are concrete. Can class be abstract even if does not have any abstract methods? If yes Whats the use?

Thanks

+6  A: 

One cannot instantiate abstract classes so you have to subclass them in order to use it.
In the subclass you can still implement your own methods or override parent methods.

Maybe it doesn't make sense to use HttpServlet as standalone, but it provides necessary default functionality in a certain context. You can subclass HttpServlet to serve this context and to have access to its functionality.

A subclass of HttpServlet doesn't have to implement methods in order to make its own functionality work.

Felix Kling
+3  A: 

It's a matter of intent. If the class is abstract, you can't create an instance of that class - only of a subclass.

I'm not strong on Java, but my guess is that HttpServlet provides default implementations of it's methods, but that you're expected to override some of them. It still makes little sense to have an unspecialised instance of that class, so it's abstract so the compiler drops a hint to anyone who tries.

Steve314
+1, The default behaviour of `HttpServlet`'s methods would lead to *very* boring web pages...
Adam Paynter
Surely not as boring as http://www.cavaliers.org/john/boring.html ?
Steve314
+2  A: 

Marking a class as an abstract even when there is a concrete implementation for all methods would be helpful in cases where you are not sure if the class design is complete or there are chances that you plan to add some methods later. Changing a class that has been declared abstract to be made not abstract later doesn't break the compatibility with pre-existing binaries where as other way round breaks compatibility.

sateesh
+17  A: 

In the case of HttpServlet, the point is that servlet programmers typically don't want their servlet to support all 4 oft the main HTTP methods (POST, GET, PUT, DELETE), so it would be annoying to make the doGet(), doPost(), etc. methods abstract, since programmers would be forced to implement methods that they don't need. Therefore, HttpServlet provides a default implementation for all those methods that does nothing except return an error statuscode to the client. Programmers can override the methods they need and not worry about the rest. But actually using the HttpServlet class itself make no sense (since it does nothing useful), so it's abstract.

And there you have a great example for when it can make sense to have an abstract class without any abstract method.

Michael Borgwardt
It's indeed a great example. It's by the way also called Template Method pattern.
BalusC