0

I have class A and class B which extends A.

class A {

    public void play(){
      System.out.println("A"):
    }
}

class B extends A {
    @Override
    public void play(){
      System.out.println("B"):
    }
}

Lets say I have something like that:

 A myObj = new B();
 ((A)myObj).play;

This is still show B in the system out. Shouldn't it show A since I upcasted it and I executed play. How can I call the super play given that my object is of type B?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Snake
  • 14,228
  • 27
  • 117
  • 250

3 Answers3

2

Casting a reference does not change the underling object.

myObj is a variable that stores a reference to an A object. In your code, that object is a B.

When you cast myObjt to a B you're narrowing the reference to a subclass so that you can invoke one of its methods. This does nothing to the B object.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
1

The cast is irrelevant. The whole point of polymorphism is that the version of the method that gets called depends on the class of the object (that is, what it was created as), and not on the type of the referring expression (that is, what it was declared as or cast to).

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
0

((A)myObj) is not doing nothing here, no point casting integer to integer.

Also typecasting doesnt change object reference.

Vinay Pandey
  • 8,589
  • 9
  • 36
  • 54