Q1. Can we write constructors in servlets ?
Ans. Container creates servlet instances using its no-argument constructor. So the answer is, You can write constructor but, if you write a constructor with arguments, you need to provide a no-arg constructor also.
Q2. Why do we use init method to initialize a Servlet ? Why can’t we use constructor ?
Ans. B’cose interfaces don’t allow to specify constructor signatures. This is a bit high level answer. All servlets either directly or indirectly implements the GenericServlet interface. In other words, you define the rules that a servlet should follow using the GenericServlet interface. But, how do you specify that a ServletConfig object should be passed as argument when creating a Servlet instance. You can’t declare a constructor rule in interface.
You can’t do this,
public interface GenericServlet {
public GenericServlet(ServletConfig sc) {
}
}
So the only way is to define a seperate init method. The name init is arbitrary, just a meaningful name.
public interface GenericServlet {
public init(ServletConfig sc) {
}
}





