Can we put costructor in place of init() method . if yes how it works plz xplain in detail??

Showing Answers 1 - 15 of 15 Answers

tarunarora

  • Nov 15th, 2006
 

First of all constructor and init methods are two absolutely different things in Context of a Servlet Class....they both cannot replace eachother.Constructor jst means...initializing an object in the memory...n even if u don put a constructor in your Servlet class JVM will put a default no-arg constructor...but u cannot do anything and neither u shd write any code like binding resources in the constructor of a servlet..bcos at this point ur Servlet is jst like another object in the memory and not a Servlet actualy.It only bcomes a Servlet when the Servlet Container calls its first lifetime method init()....it is at the completion of this method that an normal object becomes a Servlet....bcoz its lifecycle is now controlled by Servlet Container and not directly by JVM. So it is here that u shd right all that code to acquire resources for the servlet.Hope this will resolve ur doubts....Thnx

  Was this answer useful?  Yes

sampath

  • Nov 30th, 2006
 

we can use constructor instead of init() but the constructor must be of zero aurguments.

  Was this answer useful?  Yes

litha

  • Jan 9th, 2007
 

Well, in JDK 1.0 (for which servlets were originally written), constructors for dynamically loaded Java classes (such as servlets) couldn't accept arguments. So, in order to provide a new servlet any information about itself and its environment, a server had to call a servlet's init() method and pass along an object that implements the ServletConfig interface. Also, Java doesn't allow interfaces to declare constructors. This means that the javax.servlet.Servlet interface cannot declare a constructor that accepts a ServletConfig parameter. It has to declare another method, like init(). It's still possible, of course, for you to define constructors for your servlets, but in the constructor you don't have access to the ServletConfig object or the ability to throw a ServletException.

  Was this answer useful?  Yes

sunil.yadav

  • Jan 31st, 2007
 

constructor makes a simple object, when the container call init() on this simple object, now the simple object has become servlet which can serve the request.

  Was this answer useful?  Yes

webcontainer create an object for servlet class.for createing an object use the newInstance() method.this object automaticaly create a defaultconstructor so we can not create parametarised constructior for this object.praveen kumar sakhamudi

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions