Monday, October 24, 2005

Explain the difference between init(ServletConfig config) method and init() method. API says simply override no arg init() method which will be called by init(ServletConfig config) method? What does this imply?


Code decompiled from GenericServlet in javax.servlet package.

----------------------------------------------------------------------------

public void init(ServletConfig config) throws ServletException {

this.config = config;

init();

}

public void init() throws ServletException {

}

private transient ServletConfig config;

-----------------------------------------------------

If we look at the above code we can understand that the init() method with no args is called from within the init(ServletConfig config) method.

If we override the init(ServletConfig config) method that takes a ServletConfig then

super.init(config) should be the first statement inside that overriden method.

Because the container creates a ServletConfig instance and passes that instance to the init method of the GenericServlet where that config instance is assigned to the local private copy of that class. (private transient ServletConfig config;)

Code decompiled from GenericServlet in javax.servlet package.

----------------------------------------------------

public ServletConfig getServletConfig() {

return config;

}

----------------------------------------------------

If we override the init(ServletConfig config) method that takes a ServletConfig and didn't specify the super.init(config) then the local copy of the ServletConfig instance will not be initialized and when you try to use the getInitParameter(String str) of the ServletConfig interface (which is not been initialized to some value in the GenericServlet class) NullPointerException will be the result.
This is a very good example of Encapsulation as the instance variable [
private transient ServletConfig config;] is kept private and the getter methods are used to get that particular instance.


0 Comments:

Post a Comment

<< Home