Wednesday, June 18, 2008

Can we have constructors in Servlets?

Question: Can we have constructors in Servlets?

Answer: Yeah... we can have constructors in Servlets (the classes which implement javax.servlet.Servlet interface), but we generally don't have them for the following reasons:-

  • Initialized by the Web Container - Servlets are not instantiated explicitly unlike regular Java classes as they additionally require a special ServletConfig object for their initialization, which can only be created by the Web Container as it contains an instance of ServletContext as well, which is container environment based. There are two approaches, which a Servlet Container follows to initialize the servlets. Read more in this article - Preinitialization & Lazy Initialization of Servlets >>. Constructors are used to initialize an explicitly created object and probably to emphasize the implicit instantiation and initialization, servlets use a different method 'init()' for their initialization.
  • Interfaces don't contain constructors - Servlet (javax.servlet.Servlet) is only an interface and not a class. Interfaces in Java don't have any constructors as it doesn't make sense for them to have one. And a constructor of an implementing class can of course not be declared in the Servlet interface for the obvious reason that we wouldn't be knowing the name of the implementing class(es). The classes implementing them may certainly have a constructor, but as specified above, those constructors won't serve their usual purpose. The Servlet Container will only use the init() method to initialize the servlet.

Thus we see that even though it's possible to have a constructor in a class implementing the Servlet interface, it's advised not to have it for the simple reason that the constructor will not serve its usual purpose. we may think of init() as a renamed constructor for a servlet and everything which we would have like to put in the constructor can be put inside the init() method. In fact, servlets provide additional ways of specifying initialization parameters - by specifying them in the Deployment Descriptor (web.xml).


1 comment:

Java Experience said...

A few more reasons for why servlets don't have constructors:
servlets don't have constructor