Search code examples
javaservletsapplet

Why we use init() rather Constructor


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

Please answer in reference of Servlet and Applet.
How does the init() of Applet differ from Servlet?


Solution

  • 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