Java Polymorphism: Reference Types, Casting and Virtual Method Calls (OCP 21)
Polymorphism for the OCP 21 exam: object type versus reference type, implicit upcasts and explicit downcasts, ClassCastException, casts the compiler rejects (including final, record and sealed types), instanceof patterns, virtual method calls, and hidden fields and static methods.
kvi5hnuCode Sprout team member8 min readOn this page
Polymorphism means one object can be used through many types. A Java object can be referenced by a variable of:
- its own class
- any superclass, all the way up to
Object - any interface the class (or one of its superclasses) implements
Assigning to any of these supertypes needs no cast. The reverse direction does, and the rules for when that cast compiles and when it fails at run time are a favorite exam topic.
Object type versus reference type
interface Rechargeable { int batteryPercent(); }
class Vehicle { int wheels() { return 4; } }
class Bike extends Vehicle { @Override int wheels() { return 2; } }
class EBike extends Bike implements Rechargeable {
int charge = 80;
public int batteryPercent() { return charge; }
}
EBike eb = new EBike();
Vehicle asVehicle = eb; // no cast: EBike IS-A Vehicle
Rechargeable asCharge = eb; // no cast: EBike implements Rechargeable
Object anything = eb; // every object IS-A Object
There is still only one object. eb == asVehicle is true. What differs is what the compiler lets you do through each variable:
asVehicle.batteryPercent(); // DOES NOT COMPILE: Vehicle declares no such method
asCharge.charge; // DOES NOT COMPILE: Rechargeable has no field charge
asCharge.batteryPercent(); // OK: 80
Two rules capture everything:
- The object's type decides what the object actually has, and which overridden method runs.
- The reference's type decides which members the code may name at compile time.
Changing the reference type never changes the object. A cast can only give back access to members the object had all along.

Casting objects
Going up the hierarchy (subtype to supertype) is an implicit cast. Going down needs an explicit cast:
Vehicle v = new EBike(); // implicit upcast
EBike e1 = (EBike) v; // explicit downcast: compiles, and works
EBike e2 = v; // DOES NOT COMPILE: incompatible types (missing cast)
The compiler only knows the reference type. v is a Vehicle, which might or might not be an EBike, so you must say "trust me" with a cast. The JVM then checks that promise at run time:
Vehicle plain = new Vehicle();
Bike b = (Bike) plain; // compiles, then throws ClassCastException
The rules to memorize:
- Subtype to supertype: no cast needed.
- Supertype to subtype: explicit cast required.
- At run time, a cast to a type the object isn't throws
ClassCastException. - The compiler rejects casts that could never succeed.
A cast binds more tightly than the dot operator, so to call a method on the result you need extra parentheses: ((EBike) v).batteryPercent(). Writing (EBike) v.batteryPercent() casts the result of the call instead, and here doesn't compile.
Casts the compiler rejects
Between classes, the compiler allows a cast only if one class is a subtype of the other:
class Bird { }
class Fish { }
Fish f = new Fish();
Bird b = (Bird) f; // DOES NOT COMPILE: incompatible types: Fish cannot be converted to Bird
Both extend Object, but neither extends the other, so no object could be both.
Interfaces are looser. A class that doesn't implement an interface could still have a subclass that does, so the compiler usually allows the cast and leaves the check to run time:
interface Swimmer { }
class Wolf { }
Wolf w = new Wolf();
Swimmer s = (Swimmer) w; // compiles, but throws ClassCastException at run time
The exception is when no such subclass is possible:
| Cast | Compiles? |
|---|---|
| non-final class ↔ interface it doesn't implement | yes (run time decides) |
final class ↔ interface it doesn't implement | no |
| record or enum ↔ interface it doesn't implement | no (records and enums are implicitly final) |
| class ↔ sealed interface whose permitted subtypes exclude it | no (Java 17+) |
| interface ↔ interface | yes |
That last-but-one row is newer than many study materials. Since sealed types arrived, the compiler uses the permits list too. If Shape is sealed and permits only Circle, a cast from an unrelated class Tile to Shape is rejected, because no subclass of Tile could ever be a Shape.
Wrapper and library classes follow the same rules. (Integer) "7" doesn't compile, because String and Integer are unrelated final classes. (Long) obj, where obj is an Object holding an Integer, compiles and then throws ClassCastException. A cast never converts one wrapper into another.
The instanceof operator
instanceof checks the object's real type at run time, so you can test before casting. With pattern matching (article 11), the test and the cast happen in one step:
Vehicle v = pick();
if (v instanceof Rechargeable r) {
System.out.println(r.batteryPercent()); // r is only in scope where the test succeeded
}
Its compile-time rules mirror casting:
- Testing against an unrelated class doesn't compile:
fish instanceof Birdgives "incompatible types". null instanceof Anythingisfalse, never an exception.- Since Java 21, a pattern whose type is a supertype of the expression's type is allowed:
bike instanceof Vehicle vcompiles and is always true for non-null values. In Java 16 to 20 this was a compile error, so older materials may disagree.
Polymorphism and overriding
When a method is overridden, the object's version runs. This holds even when the call is written inside the parent class:
class Kettle {
int litres() { return 1; }
String label() { return "holds " + this.litres() + " L"; }
}
class BigKettle extends Kettle {
@Override int litres() { return 3; }
}
System.out.println(new BigKettle().label()); // holds 3 L
Kettle k = new BigKettle();
System.out.println(k.litres()); // 3: the object decides, not the reference
label() is defined in Kettle, but the object is a BigKettle, so this.litres() runs the override. This is called virtual method invocation or dynamic dispatch, and it's what lets a parent class work with behavior its children provide.
Some consequences worth knowing:
finalmethods can't be overridden, so they always run the declared version.privatemethods aren't inherited, so they aren't overridden either. IfKettle.litres()wereprivate,label()would callKettle's version, and alitres()inBigKettlewould be an unrelated new method.- Constructors call overrides too. If a parent constructor calls an overridden method, the child's version runs before the child's fields are initialized, so it can see
nullor0. Avoid calling overridable methods from constructors. - Overloading is decided at compile time by the reference types of the arguments, not by the objects. Only the choice among overrides happens at run time.
Calling the parent version
Use super.method() inside the subclass to run the parent's implementation:
class BigKettle extends Kettle {
@Override int litres() { return 3; }
String compare() { return super.litres() + " vs " + litres(); } // 1 vs 3
}
You can't do it from the parent side. Writing super.litres() inside Kettle refers to Kettle's own superclass, Object, which has no litres() method, so it doesn't compile.
Hidden members are not polymorphic
Fields and static methods are hidden, not overridden (article 34). For them, the reference type decides:
class Parent {
String tag = "parent";
static String kind() { return "P"; }
}
class Child extends Parent {
String tag = "child";
static String kind() { return "C"; }
}
Child c = new Child();
Parent p = c; // same object
System.out.println(c.tag + " " + p.tag); // child parent
System.out.println(Child.kind() + Parent.kind()); // CP
Calling a static method through a variable, as in p.kind(), compiles (javac warns only with -Xlint:static, and IDEs flag it) and uses the variable's declared type: Parent. Field access works the same way, and casting changes which field you see: ((Parent) c).tag is "parent".
| Member | Which version is used | Decided at |
|---|---|---|
| instance method (overridden) | the object's class | run time |
| static method (hidden) | the reference's type | compile time |
| field (hidden) | the reference's type | compile time |
| private method | the class where the call is written | compile time |
Hiding fields and static methods is legal but confusing, so avoid reusing inherited names in real code.
What's current
- Nothing in this article changed in Java 22 through 25, so the rules apply to both the Java 21 exam (1Z0-830) and the Java 25 exam (1Z0-831).
- Pattern matching (
if (a instanceof Dog d), article 11) is the current replacement for the old test-then-cast idiom, but cast rules andClassCastExceptionwork exactly as described here.
Exam traps from this article
A complete example
A small fleet shows one EBike object behind three reference types, an overridden method versus hidden fields and static methods, a successful downcast, a failing one, and polymorphic processing with instanceof patterns.
import java.util.List;
public class Solution {
interface Rechargeable {
int batteryPercent();
}
static class Vehicle {
static String category() { return "vehicle"; } // static: hidden, not overridden
String name = "vehicle"; // field: hidden, not overridden
int wheels() { return 4; }
String describe() { // calls the overridable method
return getClass().getSimpleName() + " with " + wheels() + " wheels";
}
}
static class Bike extends Vehicle {
static String category() { return "bike"; }
String name = "bike";
@Override int wheels() { return 2; }
String parentWheels() { return "parent says " + super.wheels(); }
}
static class EBike extends Bike implements Rechargeable {
private final int charge;
EBike(int charge) { this.charge = charge; }
@Override public int batteryPercent() { return charge; }
}
static final class Truck extends Vehicle {
@Override int wheels() { return 6; }
int payloadKg() { return 3500; }
}
static String inspect(Vehicle v) {
// Pattern matching: test and cast in one step, no ClassCastException possible
if (v instanceof Rechargeable r) {
return v.describe() + ", battery " + r.batteryPercent() + "%";
} else if (v instanceof Truck t) {
return v.describe() + ", payload " + t.payloadKg() + " kg";
}
return v.describe();
}
public static void main(String[] args) {
// One object, three reference types
EBike eb = new EBike(80);
Bike asBike = eb; // implicit upcast
Vehicle asVehicle = eb; // implicit upcast
Rechargeable asCharge = eb; // interface reference
System.out.println("same object? " + (eb == asBike && asBike == asVehicle && asVehicle == asCharge));
// Overridden method: the OBJECT decides
System.out.println("asVehicle.wheels() = " + asVehicle.wheels());
// Fields and static methods: the REFERENCE type decides
System.out.println("asVehicle.name = " + asVehicle.name + ", ((Bike) asVehicle).name = " + ((Bike) asVehicle).name);
System.out.println("Vehicle.category() = " + Vehicle.category() + ", Bike.category() = " + Bike.category());
System.out.println(eb.parentWheels());
// Explicit downcast back to the subtype
Bike back = (Bike) asVehicle;
System.out.println("downcast ok, wheels " + back.wheels());
// A bad downcast compiles but fails at run time
Vehicle plain = new Vehicle();
try {
Bike wrong = (Bike) plain;
System.out.println(wrong.wheels());
} catch (ClassCastException e) {
System.out.println("ClassCastException: a Vehicle is not a Bike");
}
// Polymorphic processing
List<Vehicle> fleet = List.of(new Vehicle(), new Bike(), new EBike(45), new Truck());
for (Vehicle v : fleet) System.out.println(" " + inspect(v));
}
}
Output:
same object? true
asVehicle.wheels() = 2
asVehicle.name = vehicle, ((Bike) asVehicle).name = bike
Vehicle.category() = vehicle, Bike.category() = bike
parent says 4
downcast ok, wheels 2
ClassCastException: a Vehicle is not a Bike
Vehicle with 4 wheels
Bike with 2 wheels
EBike with 2 wheels, battery 45%
Truck with 6 wheels, payload 3500 kg
Points to notice:
- All four variables point at the same object, so
==istruefor each pair. asVehicle.wheels()prints2: the object is anEBike, which inheritsBike's override.asVehicle.nameisvehicle, while((Bike) asVehicle).nameisbike. A field depends only on the reference type, and the cast changes it.super.wheels()insideBikereaches the parent version,4.(Bike) plaincompiles becauseBikeis a subclass ofVehicle, but the object is only aVehicle, so the JVM throws.describe()lives inVehicle, yet calls each object's ownwheels().getClass()also reports the real class.
Common questions
Is a cast a conversion? No. A reference cast never changes the object. It only changes how the compiler lets you use the reference, and adds a run-time check.
Why does the compiler allow some casts that always fail? It only rejects casts it can prove impossible from the declared types. With non-final classes and interfaces, some future subclass could make the cast valid, so the compiler leaves the check to run time.
When should I use instanceof instead of overriding?
Prefer overriding: put the varying behavior in the subclasses. Use instanceof patterns (or a pattern switch over a sealed type) when you can't change the classes, or when the logic belongs outside them.
Summary
- An object can be referenced by its own type, any supertype, or any interface it implements. The object never changes, only the access.
- Upcasts are implicit. Downcasts need an explicit cast and can throw
ClassCastException. - The compiler rejects casts and
instanceoftests between types that can't overlap: unrelated classes, and final classes, records, enums or sealed types versus interfaces they can't implement. - Overridden instance methods are chosen by the object at run time, even when called from the parent class.
super.method()reaches the parent version. - Fields, static methods and private methods are chosen by the reference type at compile time.
Practice quiz
Test yourself with the polymorphism quiz: 10 exam-style questions with explanations.
You've finished Chapter 7. Check your understanding of the whole chapter with the Chapter 7 review quiz: 20 mixed questions on interfaces, enums, sealed classes, records, record patterns, nested classes and polymorphism.
Previous: Java Local and Anonymous Classes (OCP 21)
Next: Java Lambda Expressions: Syntax, Parameters and Bodies (OCP 21)
Related reading
- Java Local and Anonymous Classes (OCP 21)
- Java Nested Classes: Inner Classes and Static Nested Classes (OCP 21)
- Java Sealed Classes and Interfaces: sealed, permits, final and non-sealed (OCP 21)
- Java Interfaces: Declaring, Implementing and Inheriting Abstract Methods (OCP 21)
- Java Abstract Classes and Abstract Methods (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.