Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why we can't initialize a servlet using constructor itself?

Why do we have to override init() method in Servlets while we can do the initialization in the constructor and have web container call the constructor passing ServletConfig reference to servlet while calling constructor?

Ofcourse container has to use reflection for this but container has to use reflection anyway to call a simple no-arg constructor

like image 231
Reddy Avatar asked Nov 28 '22 19:11

Reddy


1 Answers

Since a constructor can not be part of an interface, it can not be "formally" specified within the Servlet API, unlike normal methods. Moreover, since Java has no destructors, a destroy method is needed anyway, so it defining the corresponding init method makes the API more consistent and easier to use.

Using reflection to detect/verify constructor parameters would just unnecessarily complicate things, and I don't see any added value.

like image 88
Péter Török Avatar answered Dec 04 '22 10:12

Péter Török