2

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 :)

1
  • s1 already has type Shape...so the cast doesn't have any sense Commented Dec 28, 2015 at 21:28

2 Answers 2

3

Casting does not change what the object is, it simply changes how the compiler should look at that object.

So even if you "think" of a Circle to be "just a shape" it still stays a Circle.

The only way for a Circle1 to call Shape's draw would be from within Circle1 by a call to super.draw()

Sign up to request clarification or add additional context in comments.

Comments

0

When you explicitly (or implicitly) cast an object to a super type the methods will always obey the implementation of the class used to construct the object. In your case, because your object was constructed with new Circle2(), it will always be a Circle2, even if you cast it. In fact, there is an easy way for you to see that. Just add the following lines to your code:

Shape s2 = (Shape) s1;
System.out.println(s2.getClass().getName());

This prints the exact class that your s2 object (casted from s1) belongs to :) you will see it is still a Circle2.

If you want to call the super type implementation of the draw() method you need to call super.draw() instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.