*
The moose likes Servlets and the fly likes constructors are for initializing instance variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "constructors are for initializing instance variables" Watch "constructors are for initializing instance variables" New topic
Author

constructors are for initializing instance variables

sai prasanna
Ranch Hand

Joined: May 02, 2005
Posts: 167
hi
Generally constructors are for initializing instance variables. but in servlets we are using Life cycle method init(ServletConfig sc) for getting initialization parameters.As servlet is instantiated by container is this the reason we are not writing our own constructor in servlet? if not what is the reason please explain if we pass our own constructor what will be the containers and servlet reaction
thanks in advance
saiprasanna
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12769
    
    5
If your servlet class has a constructor with parameters, it will never be called by the servlet container.

If your servlet class has a public arg-less constructor, it will be called.

Generally speaking, instance variables one might use in a servlet are related to the servlet environment - for example initialization parameters read from web.xml. Therefore they should be initialized in init as per the API.

Incorrect use of servlet instance variables is the cause of many beginner problems.
Bill
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: constructors are for initializing instance variables