Why we use init() rather Constructor

前端 未结 4 1436
情歌与酒
情歌与酒 2021-01-20 05:00

why do we need init() rather than a constructor?

Please answer in reference of Servlet and Applet.
How does t

4条回答
  •  广开言路
    2021-01-20 05:38

    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.

提交回复
热议问题