In order to try and explain the important topic of polymorphism in Java, I will use the following class hierarchy as an example:
1 2 3 4 5 6 7 |
class Device { } class MobileDevice extends Device {} class DesktopDevice extends Device {} class WearableDevice extends Device {} |
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 aDevice
and is also anObject
and so it can be used whereverDevice
orObject
objects are called for - But the reverse is not necessarily true: a
Device
may be aMobileDevice
, but it also may not be
There are two important concepts involved in the this example:
Implicit casting (Widening) |
|
---|---|
Explicit casting (Narrowing) |
|
Below are examples of both concepts:
1 2 3 4 5 6 7 8 9 10 |
// WIDENING EXAMPLE MobileDevice md = new MobileDevice(); // OK: a MobileDevice is always a Device Device d = md; // OK: a Device is always an Object Object o = new Device(); |
1 2 3 4 5 6 7 8 9 10 |
// NARROWING EXAMPLE Device d = new MobileDevice(); // OK: d can be a MobileDevice (runtime error if it's not) MobileDevice md1 = (MobileDevice) d; // compiler error (no casting) MobileDevice md2 = d; |
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:
1 2 3 4 |
Device d = new MobileDevice(); int type = d.getType(); |
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 methods). 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 |