Inheritance and Override Methods

I have class A and class B that extends A

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

Let's say I have something like this:

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

The system still displays B If it does not show A , since I raised it, and I completed the game. What can I call a super game, given that my object is of type B ?

0
java
source share
3 answers

Casting a link does not modify the underling object.

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

When you press myObjt on B you narrow down the subclass reference so that you can call one of your methods. This does nothing for object B

+2
source share

The cast does not matter. The whole point of polymorphism is that the version of the called method depends on the class of the object (i.e., that it was created as), and not on the type of the reference expression (that is, what was declared as or discarded).

+1
source share

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

Also typecasting does not change the link to the object.

0
source share

All Articles