I have a small issue with polymorphism and explicit casting. Here is the problem: I have 3 public classes:
package x;
public class Shape
{
public void draw(){
System.out.println("draw a Shape");
}
}
package x;
public class Circle1 extends Shape
{
}
package x;
public class Circle2 extends Circle1
{
@Override
public void draw ()
{
System.out.println("draw Circle2");
}
}
And my Demo class is:
package x;
public class Demo
{
public static void main (String[] args)
{
Shape s1=new Circle2();
s1.draw();
((Shape)s1).draw();
}
}
The output of this code is:
draw Circle2
draw Circle2
I understand the polymorphic behavior of s1.draw() that invokes the draw() method on Circle2.
The last line confuses me, when I do explicit casting on s1 like so: ((Shape)s1), it means that the expression ((Shape)s1) is a reference of type Shape because of the explicit casting,right?
And if that is so, why then the code ((Shape)s1).draw(); invokes the draw() method in Circle2 and not the one in Shape?
Thanks :)
s1already has typeShape...so the cast doesn't have any sense