HttpServlet
is an abstract class with all implemented methods. Why it is abstract?
The most common answer I got is, to restrict the instantiation of HttpServlet
. But there are other ways of doing it, like a private constructor will restrict the instantiation.
I can understand that they are following Template Method design pattern. If some methods are abstract, user will end up implementing all of them, even if he does not need them for his business logic.
But if HttpServlet
was not abstract, an user can still extend it and override the require methods.
At least by the dictionary meaning of the word 'abstract', its does not make any sense to me to have a abstract class with all implemented method.
Yes a combination of abstract and concrete methods are ok to have.
But if you are making a class abstract why not make those methods abstract which the sub class has to override? or may be do not declare it as abstract at all?
Like doGet()
or doPost()
is this case.
To create a servlet the class must extend the HttpServlet class and override at least one of its methods (doGet, doPost, doDelete, doPut). The HttpServlet class extends the GenericServlet class and implements a Serializable interface. This is an abstract class so, the constructor does nothing.
It is declared as a class instead of an interface to implement most of the cruft/repeatable code required for setting up a servlet. It is declared as abstract since it wouldn't make sense to instantiate a "bare bones" servlet which takes care only of the setup and doesn't contain any custom/user defined logic in it.
HttpServlet – An abstract class providing functionality to implement HTTP requests. Note that the service() method defined in the Servlet interface will now call doGet() and doPost(), which can each be implemented to provide behaviour to the Servlet.
An abstract class is used if you want to provide a common, implemented functionality among all the implementations of the component. Abstract classes will allow you to partially implement your class, whereas interfaces would have no implementation for any members whatsoever.
To have any useful behaviour, it is expected that you will have to override the methods. HttpServlet does not have useful functionality on its own.
Making its constructors private would limit the ability for subclasses to be created.
The design of HttpServlet was probably not ideal -- as on many pages, forms especially, GET and POST logic should proceed at least partly along a common path. The design idea of HttpServlet however was to offer doGet()
, doPost()
etc implementations answering a 'not supported' error depending on HTTP version. These stubs would be useful to inherit if you needed to return such an answer.
In summary, the API/ interface is complete -- but the functionality is definitively not. Thus it is declared as abstract.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With