it depends on object type at runtime that which method will be called.
you are passing an object of type PlayerPiece to the doShape method which takes GameShape as arguments and this is legal because Playerpiece extends GameShape.
Now at runtime jvm sees that object referred by shape variable is actually a PlayerPiece object and it will call the overridden method.
Here, the actual object is PlayerPiece. For method doShapes(), we upcast that. But for at runtime, the method is invoked on the actual object. Not in the reference type. This is called as Virtual Method Invocation!
If you always want to call the super class method before the child class method be executed you can use super key word in sub class method. But you can't directly call super class (which is overridden in subclass) method by using child class reference.
This is polymorphism in action. You passed in a PlayerPiece object and it was accepted
by doShapes() because PlayerPiece is indeed also a GameShape. But the object passed
remains a PlayerPiece. So PlayerPiece.displayShape() is called, not the GamePiece
version. It's the type of the object, not the type of the variable (local in this case) that
determines the procedure version called.
This may help. What if GameShape were an interface rather than a concrete class.
You could cast a PlayerPiece into GameShape (to focus on GameShape behaviors) but
a GameShape object could not be created. PlayerPiece.displayShape() would be the
only option available.
Jim...
This message was edited 1 time. Last update was at by Jim Hoglund
I tend to find it easier to think of more than one class extending the super class. If you had PlayerPiece and ChessPiece and DraughtsPiece as classes all extending GameShape then it becomes clearer to my mind how the polymorphism works.
The doShapes() method can take any object as the argument as long as it is a subclass of the GameShape object.
Additionally the doShapes method will continue to work when/if you introduce new GameShape subclass objects.
p185 of Head First Java : "...with polymorphism, the reference and the object can be different"
There is a clear example on p187 involving Animals and Vets and Dogs/Hippos (subclasses of Animal).
In your case the shape.displayShape(); [line 13] will refer to the actual object on the heap (late binding) and the corresponding subclass method will be called rather than the superclass method.
I'm still learning but this is my understanding - (might need correcting!).
Ed
This message was edited 1 time. Last update was at by Edward Kin