In order to try and explain the important topic of polymorphism in Java, I will use the following class hierarchy as an example:

Given this class hierarchy, what could we say about MobileDevice? It’s a descendant from Device (and implicitly from Object) so we could say:

  • A MobileDevice is a Device and is also an Object and so it can be used wherever Device or Object objects are called for
  • But the reverse is not necessarily true: a Device may be a MobileDevice, but it also may not be

There are two important concepts involved in the this example:

Implicit casting (Widening)
  • Assigning a subclass reference to a base class reference
  • This is always OK
Explicit casting (Narrowing)
  • Assigning (casting) a base class reference to a subclass reference
  • This is OK at compile time but could lead to a runtime error if the assigned reference is not referencing a subclass instance

Below are examples of both concepts:

Virtual Method Invocation

Let’s say the class Device has a method getType() that it is overridden in the subclass MobileDevice. When the following code is run:

What method is actually invoked? The one in MobileDevice or the one in Device? Yes… it’s the one in MobileDevice because the JVM knows at runtime that the object referenced by d is a MobileDevice even although the type of the reference variable is Device.

This is known as virtual method invocation or dynamic binding and it works only for instance methods (non-static mehtods). For the exam, it’s very important to know how virtual method invocation works, so be sure you understand the following table:

Kind of member  When you access a member of this kind, what type is invoked?
 Instance methods (non-static) The type of the actual object that is referred by the variable
 Static methods The type of the reference variable
Fields (static or not) The type of the reference variable

Leave a Reply