We all know that an object of a superclass cannot be casted to an object of a subclass.Now here we get the deviation from this rule
(Just to be clear,PageContext is a subclass of JspContext.Actually,it's a interface Hierarchy.Check the following link
Java Class Hierarchy)
public void doTag()throws JspException,IOException
out.println("Tag gets going");
PageContext context=(PageContext)getJspContext(); //Here is a typecast from JspContext to PageContext
getJspContext().setAttribute("names", "here they are");
More formally,I am using reference variable of type pagecontext for JspContext object returned by getJspContext() method.I am not getting ClassCastException.
Bear Bibeault wrote:There is no "deviation from the rule".
What is being returned from the method is a PageContext instance.
Remember that it is possible to refer to an extended class by one of its ancestors. In this case, the method could return any class that extends JspContext. In this case, it's a PageContext.
but when we see the return type of getJspContext() it returns JspContext and if getJspContext() was to return pageContext instance,there would have been no need to cast the result of getJspContext() method to PageContext.
Then why do we cast it?
Swapnil Dharane wrote: if getJspContext() was to return pageContext instance,there would have been no need to cast the result of getJspContext() method to PageContext.
Incorrect. This is just basic Java. If you have a reference to a subtype of an instance, you need to cast it to use it as the extended type.
All right.So you want to say that getJspContext() method returns a PageContext instance.But we still need to cast it
Can you explain this with an example related to PageContext and JspContext?
As we can cast JspContext to PageContext,I can see only two possibilities.Correct me if I am wrong
1)PageContext is not exactly a subclass of JspContext.If it was a subclass of jspContext we could not cast JspContext reference to it.
2)PageContext and JspContext have some relationship other than inheritance.