This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
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
Author

init method or constructor?

Kalai Selvan
Ranch Hand

Joined: Jul 07, 2004
Posts: 79
Hi,
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
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

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.
 
GeeCON Prague 2014
 
subject: init method or constructor?