Wednesday 8 February 2017

Can we create constructor in Servlets?


One of the basic questions that has been asked in the interview in a web development profile is can you create a Constructor inside a Servlet?

The answer is bit complicated and the goal of interviewer is just to test that how long has the interviewee been in the web development as only experienced developers know the answer to this
question. Of course we can create a constructor inside a servlet as it is also a class and like all the other classes Servlets can also have a constructor. But we must not keep this in practice because of two reasons.

First is that after JDK 1.0 all the dynamic classes in java have to mandatory use only the default constructor for creating the class object and if the user creates a parameterized constructor inside the servlets and forgets to create a default constructor then it will not allow the servlet to create an Object  and JAVA does not allows user to enter the code that may result in ambiguity.

Second is that Servlets are not instantiated using the reference of the class object rather servlets are instantiated by webcontainer using Java Reflection using class.newInstance() method which uses class name for instantiating the class object so when the user creates the constructor in the servlet the constructor actually is never executed. Answer is very simple as the servlet lifecycle does not allows user to create the object of servlet and the servlet are instantiated only by webcontainer when the client request arrives

No comments:

Post a Comment