Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Difference between init and servlet constructor

 
georgy jacob
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Whats the purpose of the init method ? why didnt they just use the Servlet constructor for initialising purpose rather than using an init .
 
Mani Ram
Ranch Hand
Posts: 1140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a frequently asked question in Javaranch. Search the Servlets forum. You can find many discussions there on this topic
 
Paul Bourdeaux
Ranch Hand
Posts: 783
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is actually one of my favorite questions because it is an extremely important difference, but one that a lot of people have a hard time grasping. I will give you a little bit of background on it, but then I encourage you to search the forums and read the discussions.

The constructor is called by the container simply to create a POJO (plain old java object). It is not really a servlet (or at least it cannot do any servlet like things) until it has been initialized. As a developer, you should never override the servlet's constructor.

The init method initializes the servlet, and gives it references to things like the servlet context. If you want something to happen when a servlet is initialized, override the no-arg init method and put it there.
 
georgy jacob
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot for the information.Now i have understood it
 
Arvind Sampath
Ranch Hand
Posts: 144
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As a developer, you should never override the servlet's constructor.



Whats wrong in overriding the servlet's constructor ? Anyways the super class' constructor would be called from our our constructor. Isnt it ?

Cheers,
Arvind
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic