7

Why do we need an init() method in servlet? Can't we use the constructor to initialization?

coder
  • 2,239
  • 5
  • 22
  • 20
  • See [my answer to a similar question](http://stackoverflow.com/questions/1276082/constructor-in-servlet/2659597#2659597). – gawi Apr 17 '10 at 19:07

1 Answers1

18

Because Servlet is an interface, not an abstract class. Constructor arguments cannot be specified on an interface, so the ServletContext needs to be specified on a normal method signature.

This allows the application server to know how to initialize any Servlet implementation properly.

Another solution would have been to require, but not enforce at compile time, a constructor taking ServletContext. The application server would then call the constructor via reflection. However, the designers of the Servlet specification did not chose this path.

Darron
  • 21,309
  • 5
  • 49
  • 53