Hi I am studying servlets I read that servlets are java programs but there are no constructor in servlet... Can anybody elaborate on it?
There are as in any other java class, but you don't need to invoke it. The webcontainer will call it for you.
Most servlets do not hold instance data, hence, most of adding code in the constructor doesn't make any sense.
There is a constructor in servlet (take a look at HttpServlet, for example), but usually the web container will take care of calling it for you.
However, when you are implementing a servlet, you normally are concerned with just overriding the doGet()
and doPost()
method (or the service()
method, if you are working with other than HttpServlet
)
Ya we can definitely have constructor in servlet.Even you can use the constrctor in servlet for initialization purpose but this type of approch is not so common.You can perform common operations with the constructor as you normally do.The only thing is that you cannot call that constructor explicitly by the new keyword as we normally do.In the case of servlet servlet container is responsible for instentiating the servlet so the constructor is also called by servlet container only.