-1

I was just curious which could get called first internally.

I am very much aware that we are not supposed to have constructors in Servlets & it's not good & it spoils the use of Init(),etc. But we DO can have constructors in servelts.

Just any idea? I guess Init() is called by the container itself when placing the servlet in the servlet pool, yet what about a constructor.

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
Ashok Raj
  • 444
  • 6
  • 25
  • You can find your answer here: [Difference between each instance of servlet and each thread of servlet in servlets?](http://stackoverflow.com/q/2183974/1065197) – Luiggi Mendoza May 22 '14 at 19:58
  • Note: I'm not marking your question as a duplicate because it is not a duplicate of that question. But part of the accepted answer solves your problem. – Luiggi Mendoza May 22 '14 at 19:58
  • @LuiggiMendoza thank you :) it clearly explains the micro steps of servlet initiation. But I'm afraid it ain't got anything on constructor. – Ashok Raj May 22 '14 at 20:01
  • Covered in this line: `Class.forName(servletClass).newInstance()`. This will invoke the constructor of your servlet. – Luiggi Mendoza May 22 '14 at 20:02

1 Answers1

1

The constructor is called first or else there would be no object to call init() on. And yes, the init() method is indeed called by the container. The container might decide to re-init a servlet (could possibly prune some of its related object graphs when no activity and re-init it when needed to free memory). If you put any initialization type code in the constructor, it won't get recalled.

http://docs.oracle.com/javaee/5/tutorial/doc/bnafi.html

mprivat
  • 21,582
  • 4
  • 54
  • 64
  • You should add that as a general rule, you create a new instance of an object you have to create it using a class constructor through the `new` keyword. Only then, you can call the methods of the object, and `init` is simply a method. – Luiggi Mendoza May 22 '14 at 20:06