Hi Hamid ,
The problem here is that
Java does not know that b is a object of type sub. For example consider the classic Java example -
Base Class -
Shape is the base class,
1st inheritance step -
Triangle is a sub class of Shape. - Triangle is a type of Shape
Circle is a sub class of Shape. - Circle is a type of Shape
Rectangle is a sub class of Shape. - Rectangle is a type of Shape
2nd inheritance step -
IsocelesTriangle is a sub class of Triangle
EquilateralTriangle is a sub class of Triangle
Square is a sub class of Rectangle
Now, in the structure above, we can define -
Shape s = new Shape();
Triangle t = new Triangle();
Rectangle r = new Rectangle();
IsocelesTriangle = new IsocelesTriangle();
In all these cases, a handle is declared and then initialized to a certain object. Here, the handle and object are of the same type. When we downcast (that is what you are trying to do in the casting statement in your code), Java does not know whether the object you are downcasting is which kind of object. To clarify -
Take Shape s = new Shape();
here, Shape type of handle, s is assigned to a Shape object. As per you, we should be able to downcast the Shape object to a Triangle or a Circle or a Rectangle. Taking this logic, we should be able to further downcast s to a IsocelesTriangle or Square. But, the most important point here is that how do we know s is a IsocelesTriangle or Rectangle or Triangle? So, Java will give an error.
A rule of thumb or an easy way to understand what is allowed is -
Java will maximum downcast any handle declaration (on the left side of the equal to sign) to the class of the object created (on the right hand side of the equal to sign).
thus, if we write Shape s = new IsocelesTriangle();
we can downcast s to Triangle or to IsocelesTriangle.
So, in your code -
if you write -
Base b = new sub();
sub s = (sub)b;
then it will work. Even the following will work -
Base b = new sub1();
sub s = (sub)b;
sub1 t = (sub1)b;
I hope this clears up the matter fully.
Niraj