File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes Why init() when there is constructor? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Why init() when there is constructor?" Watch "Why init() when there is constructor?" New topic

Why init() when there is constructor?

Geeta Sawant

Joined: Oct 06, 2005
Posts: 4
Why isn't constructor enough for initializing a servlet?

Bear Bibeault
Author and ninkuma

Joined: Jan 10, 2002
Posts: 63868

Because in the init call you usually want access to the servlet context and servlet config objects whch have yet to be created when the constructor would be called.

[Asking smart questions] [About Bear] [Books by Bear]
Eddy Lee Sin Ti
Ranch Hand

Joined: Oct 06, 2005
Posts: 135
The init() is part of the servlet life cycle management facility. Instead of using constructor, which is invoked when the instance is created, using a well defined, common life cycle method would help in more advanced management. In other words, the life cycle methods defined in javax.servlet.Servlet provide a contract where all servlet have to comply. You cant define constructor method in java interface right?

SCJP, SCWCD, SCJWS, IBM 700,IBM 701, IBM 704, IBM 705, CA Clarity Technical<br /> <br /><a href="" target="_blank" rel="nofollow"></a>
Paul Bourdeaux
Ranch Hand

Joined: May 24, 2004
Posts: 783
This is a often asked question in this forum, and rightfully so, as it is an important part of understanding the lifecycle of a servlet. Bear summed it up in his response, but if you want to see some more in depth answers, search this forum for "init() constructor" and you will find several threads dealing with this issue.

If you still have questions after looking, please post them!

“Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning.” - Rich Cook
sureshreddy puli

Joined: Sep 28, 2005
Posts: 29
It is part of servlet life cycle designed by javasoft.And main purpose of init() is to retrive configuration parameters from web.xml.It is not possible to get initialization parameters through constructor and webcontainer accepts only default constructor. If u develop a servlet with parameterized constructor, it(webcontainer) raise an error.
I agree. Here's the link:
subject: Why init() when there is constructor?
It's not a secret anymore!