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

init method or constructor?

Kalai Selvan
Ranch Hand

Joined: Jul 07, 2004
Posts: 79
Why init method is required in servlet, can't constructor serve the same purpose?

Thanks in advance.

Kalai Selvan T.
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

Because servlets are created according to textual data in web.xml or a URL, so instances are created like this:

which uses the no-argument constructor. But a servlet needs various initialization parameters to set itself up, so the designers of the servlet APIs added an init() method to which the container could pass the initialization arguments.

Now, in JDK1.2, the java.lang.reflect package was added, and it's now possible to do the equivalent of passing constructor arguments to an object created via newInstance(). But the servlet API was first defined before JDK 1.2 came out, so the init() method was the only way to do things.

Note that applets also have an init() method, for very similar reasons.

[Jess in Action][AskingGoodQuestions]
Kalai Selvan
Ranch Hand

Joined: Jul 07, 2004
Posts: 79
Hi Ernest,
Thanks for the brief explanation.....

Kalai Selvan T.
I agree. Here's the link:
subject: init method or constructor?
It's not a secret anymore!