Why not declare a constructor in servlet?

06/05/2008

Technically you can define constructors in servlet. But, the declared constructor cannot access the ServletConfig object or throw a ServletException.

Then why is it not customary to declare a constructor in a servlet? Because the init() method is used to perform servlet initialization. In JDK 1.0 (servlet were written in this version), constructors for dynamically loaded Java classes such as servlets cannot accept arguments. Therefore init() was used to initialize by passing the implemented object of ServletConfig interface and other needed parameters.

Also, Java constructors cannot be declared in interfaces. So, javax.servlet.Servlet interface cannot have a constructor that accepts a ServletConfig parameter. To overcome this, init() method is used for initialization instead of declaring a constructor.

this information is very usefull, thanks u so much . keep posting nice infomation.

Anonymous on July 19th, 2010 10:16 am

Really thanks for providing such an useful information…

Anil R. Chinchawade on August 4th, 2010 6:40 pm

Nice Information.

Ravi on August 18th, 2010 5:15 am

thank u very much for providing use full Q&A’s.

accessor on May 16th, 2011 3:14 pm

Superb

Nagraj on October 3rd, 2011 1:30 pm

thank you for providing the detailed information.
k.L N SWAMI
kswami53@gmail.com

swami on January 29th, 2012 7:16 am

THANK GOD

Anonymous on March 29th, 2012 2:13 pm

Can you please tell me who calls this init() and when servlet class is instantiated?

Alps on April 5th, 2012 3:02 pm

The default constructor is call to create the instance after that init() method is call to convert instance to servlet.

Anonymous on May 2nd, 2012 8:23 pm


Email:

about
I am Joe, author of this blog. I run this with loads of passion. If you are into java, you may find lot of interesting things around ...more about me. Google+
java badge
Home