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.
You need both, but they perform different activities, your constructor executes at the time the object is created through a call to new, but for some type of objects where you don't control their creation, or you would rather execute some code not only after the object is created but is fully intialized, then you need an special method that someone is going to call to signal that the object is ready.
That is the case specially for objects that are not managed by you, but the server, framework or whoever manages these objects.
You should see this methods as a commodity provided for you on the top of the code that this object will execute on the constructor
The init()
method creates and loads the servlet. But the servlet instance is first created through the constructor (done by Servlet container). We cannot write constructors of a servlet class with arguments in servlet (It will throw Exception). So, They provided a init()
method that accepts an ServletConfig object as an argument. ServletConfig object supplies a servlet with information about its initialization (init) parameters. Servlet class cannot declare a constructor with ServletConfig object as a argument and cannot access ServletConfig object.
More info at: http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Servlets6.html
init() method is invoked only once and therefore only one instance of the controls will be created.