ServletA & ServletB are two separate class extending HttpServlet. They both have init() method.
some of the variable & methods define in ServletA are also required in ServletB, is it the good idea to for ServletB to extend ServletA and also calling super.init() from ServletB.init() method. in this case ServletA.init() will be called twice. is it right or wrong
I think there is some confusion about inheritance here...
If you have two class files (A and B) and B extends A; calling a super.methodName() method in an instance of B will not cause an methods of a separate instance of class A to be called.
In the case of servlets.. If you create two servlet class files (again A, and B) and then deploy two servlets in a container (Let's say AServlet and BServlet, each being an instance of class A, and B respectively); deploying BServlet will not cause AServlet's init method to be called.
In other words, an instance of BServlet is still only one servlet as far as the container knows. The container doesn't know or care that there is a superclass (AServlet) tucked away inside of BServlet.
The servlet B is having servlet A in encapsulated form.
You have a grave misunderstanding regarding how Java works. When a class is extended, there is no "encapsulated" form. That's the difference between containment and inheritence.
If B extends A and B defines an init() method, B's init will be called once and A's will never be called. If B does not implement init, then it will inheret A's and it will be called once. [ September 15, 2006: Message edited by: Bear Bibeault ]
I had a feeling this would happen and was trying to figure out how to word an explaination that would make it clear.
When you inherit from a class, there is, in effect, an instance of that superclass living inside instances of the subclass. This is why any print statements inside the superclass's init method were called when the subclass (servlet b) was loaded.
This is entirely different from the OTHER instance of servlet A that is running in your container.
Another way to look at it. With the given scenerio, you (in effect) had 3 servlet instances running. 1.) Servlet A (created from class A). 2.) Servlet B (created from class B). 3.) A secret copy of servlet A (call it SuperA).
The third one (the superclass to servlet B) lives inside of servlet B and is not visible to the servlet container. Only servlet B knows about it.
The init method to Servlet A was only called once. The other print statement that you saw was Servlet B calling it's (secret) superclass; not Servlet A's.