Technically you can define constructors in servlet. But, the declared constructor cannot access the ServletConfig object or throw a ServletException.
Then why is it not customary to declare a constructor in a servlet? Because the init() method is used to perform servlet initialization. In JDK 1.0 (servlet were written in this version), constructors for dynamically loaded Java classes such as servlets cannot accept arguments. Therefore init() was used to initialize by passing the implemented object of ServletConfig interface and other needed parameters.
Also, Java constructors cannot be declared in interfaces. So, javax.servlet.Servlet interface cannot have a constructor that accepts a ServletConfig parameter. To overcome this, init() method is used for initialization instead of declaring a constructor.
Comments are closed for "Why not declare a constructor in servlet?".
this information is very usefull, thanks u so much . keep posting nice infomation.
Really thanks for providing such an useful information…
Nice Information.
thank u very much for providing use full Q&A’s.
Superb
thank you for providing the detailed information.
THANK GOD
Can you please tell me who calls this init() and when servlet class is instantiated?
The default constructor is call to create the instance after that init() method is call to convert instance to servlet.
D container calls d init() cuase it controls d servlet lifecycle methods…..:)))))
can u please provide the difference between costructor and init() method in servlet
Awesome as usual….
first of all good site with good content management ….
nicely explained
good
Without calling of constructor(without creating an object of that particular servlet) how we can invoke any mathod ie init() mathod
Good Explanation
Servlet container will call the init()
“Without Calling Constructor!!!!!!!!!!!!!!” Where it’s written dude…. Of course constructor (no-arg constructor) is called by container to create instance of Servlet..
but the job of implementing “ServletConfig” interface, is done after instantiation of the Servlet, so it can’t initialize the servlet at instantiation time. So Container pass this implementation as an argument to the init() method of Servlet to complete its servletness.
Thanks for half baked and repetitive information :(
thanks
right said dude
nice explanation!! but what exactly do you mean by “servletness”?
Why the dynamically loaded classes constructor couldn’t accept arguments???
Great post Sir..
Can any one give me more clarity on why init()will be used instead of constructor.
but its still confusing. Interface doesn’t have constructors. dats right, then how come the servlet have a constructor? When a constructor is used?