Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

Servlet is a java class. So, can there be a constructor in Servlet class or not? Why?

user-image
Question added by Mohd shahnawaz khan , Associate Project , Cognizant Technology Solution
Date Posted: 2013/09/05
Mohammed Ameen
by Mohammed Ameen , Java Developer , TATA Consultancy Services Limited (TCSL)

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:

 

1)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 Servlet Container.

 

2)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).

Daanish Rumani
by Daanish Rumani , Product Manager , Publicis Sapient

Servlet itself is an interface. So there is no question of it having a constructor. Known classes that implement the Servlet interface do have constructors but they do nothing as they do need to do anything.

Constructor for HttpServlet: http://docs.oracle.com/javaee/5/api/javax/servlet/http/HttpServlet.html#HttpServlet()

More Questions Like This