The most successful people in any walks of lives may not be the most talented ones but are definately the most passionate & dedicated ones.

Thursday, February 10, 2011

Why it is not advisable to declare a constructor in servlet?

Technically you can define constructors in servlet. But, the declared constructor cannot access the ServletConfig object or throw a ServletException so placing a constructor wouldn't add much value and hence we usually don't do it.

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. Also, Java constructors cannot be declared in interfaces and javax.servlet.Servlet is an interface. Now the classes which implement this interface are GenericServlet and HttpServlet which don't do anything in these constructors [as per the API documentation].

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 is what I think, please go ahead and pen down on what you think about this and if you differ from my opinion, I assure you that you won't be the first one.



Cheers !!!
Vinay

No comments:

Post a Comment