Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need Init() method in servlets when servlets has it Construtor?

Tags:

java

servlets

in java Constructor is used for initialization why we need init() for initialization.... This question was asked in an Interview

like image 698
Mehran Junejo Avatar asked Apr 28 '14 05:04

Mehran Junejo


People also ask

Why do we need a constructor in a servlet if we use the init method?

Short answer of this question, Yes, Servlet implementation classes can have constructor but they should be using init() method to initialize Servlet because of two reasons, first you cannot declare constructors on interface in Java, which means you cannot enforce this requirement to any class which implements Servlet ...

What is the difference between constructor and init?

difference work of between init() and constructor? The constructor is called by the container simply to create a POJO (plain old java object). init method is the method which is invoked when servlet in called and it adds values to the servlet context so its a very much difference between constructor and init method...

Why we use Init method in Java?

Init method is used to start any given process. It is a method which invokes the start of the execution of any process. The init() is use to perform servlet initialization. Creating and loading objects that are used by the servlet in the handling of its request.

What is the use of constructor in servlet?

Container will only use the init() method to initialize the servlet. and The purpose of Constructor and Init method in Servlets is different. The constructor is called whenever you create a new object. Init method is called when the container loads the servlet for the first time.


1 Answers

The constructor is for normal Java initialization of an object (though typically a Servlet implementation is expected to have a no-arg constructor).

The init() method is a method provided by the Servlet interface which a Servlet container will run to configure the Servlet. The Servlet container will provide a ServletConfig object which gives the Servlet instance access to the ServletContext and other configuration elements from the deployment descriptor.

like image 101
Sotirios Delimanolis Avatar answered Nov 15 '22 22:11

Sotirios Delimanolis