in java Constructor is used for initialization why we need init() for initialization.... This question was asked in an Interview
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 ...
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...
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With