why do we need init()
rather than a constructor
?
Please answer in reference of Servlet
and Applet
.
How does t
It's a design choice. The servlet spec says that you must provide a no-arg constructor and you can override the init()
method to perform initialization tasks. They could have chosen to do otherwise and require servlets to have a single argument constructor (ServletConfig
) that optionally throws ServletException
. Technically, there is no problem with that as reflection API allows you to invoke any constructor declared in a class.
However having an init()
method allows servlet containers to pre-instantiate objects and delay their initialization. It helps separate different stages of the lifecycle.
Personally, I don't think this is a strong design choice. It would have been much more convenient to let the web application provide servlet container with pre-instantiated servlets rather than having to let the container call the constructors of various servlets.