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
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
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.
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.
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.
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.