Sub topic 4
Use Subtypes and Understand Method Dispatch
Why this chapter matters
In the last chapter you wrote a method in a subclass that replaces a method from its superclass. That is called overriding. Now you will see why overriding is useful.
Java lets you treat a subclass object as if it were an object of its superclass. When you call an overridden method on it, Java runs the version that belongs to the real object. This idea is called polymorphism. The word means "many forms". One call, such as speak(), can do different things depending on the object behind it.
This chapter covers:
- what a subtype is,
- the difference between a variable's type and an object's type,
- how Java picks which method to run,
- what you can and cannot do through a superclass reference,
- how to check and convert types safely.
Subtypes: an "is-a" relationship
A subclass is a subtype of its superclass. If Dog extends Animal, then every Dog is an Animal. Java lets you use a Dog anywhere an Animal is expected.
Animal a = new Dog("Rex");This line is legal. It is called an upcast, because you move up the class tree from Dog to Animal. You do not need to write anything special. Java does it for you, because it is always safe: a Dog has everything an Animal has.
The reverse is not automatic. A plain Animal might not be a Dog, so Java will not let you assign it to a Dog variable without a check. You will see that later in this chapter.
Two types: the variable and the object
In Animal a = new Dog("Rex"); there are two different types:
- The declared type (also called the static type) is
Animal. It is written in the code and is fixed when the program is compiled. - The runtime type (also called the actual type) is
Dog. It is the class of the object that was created withnew. It is known only while the program runs.
A variable has one declared type. The object it points to has one runtime type. These two can be different, and that difference is what makes polymorphism work.
Dynamic dispatch: which method runs?
When you call a method on a reference, Java has to decide which version of the method to run. For instance methods that can be overridden, it uses the runtime type of the object. This is called dynamic dispatch, or late binding. "Dynamic" means the choice is made while the program runs.
Here is a full example.
class Animal {
String speak() {
return "Some sound";
}
}
class Dog extends Animal {
@Override
String speak() {
return "Woof";
}
}
class Cat extends Animal {
@Override
String speak() {
return "Meow";
}
}
public class Main {
public static void main(String[] args) {
Animal a1 = new Animal();
Animal a2 = new Dog();
Animal a3 = new Cat();
System.out.println(a1.speak());
System.out.println(a2.speak());
System.out.println(a3.speak());
}
}The output is:
Some sound
Woof
MeowAll three variables have the declared type Animal. The calls look identical. Yet each one runs the method of its own object's class.
The compiler and the runtime split the work like this:
- At compile time, Java checks that the declared type has a method
speak()that you may call. If it does not, the program does not compile. - At run time, Java looks at the real object and runs the most specific version of
speak()it finds. It starts at the object's own class and moves up the chain.
Why polymorphism is useful
Polymorphism lets you write code that works with the general type and still gets the specific behavior. Look at this loop.
class Animal {
String speak() {
return "Some sound";
}
}
class Dog extends Animal {
@Override
String speak() {
return "Woof";
}
}
class Cat extends Animal {
@Override
String speak() {
return "Meow";
}
}
public class Zoo {
public static void main(String[] args) {
Animal[] animals = { new Dog(), new Cat(), new Animal() };
for (Animal animal : animals) {
System.out.println(animal.speak());
}
}
}The array holds Animal references, but the objects are of different classes. The loop does not need to know which is which. If you add a Cow class later, the loop works with it unchanged. You only write the new class.
You can also use the general type for method parameters.
static void makeNoise(Animal animal) {
System.out.println(animal.speak());
}You can pass a Dog, a Cat, or any other subclass of Animal to this method.
What the declared type allows
The declared type decides which members you can use. The compiler only knows the declared type. It does not look at the object.
class Animal {
String speak() {
return "Some sound";
}
}
class Dog extends Animal {
@Override
String speak() {
return "Woof";
}
void fetch() {
System.out.println("Fetching");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
a.speak(); // allowed
// a.fetch(); // compile error: Animal has no method fetch()
}
}The object really is a Dog and does have fetch(). But the variable's type is Animal, and Animal has no fetch(). The compiler stops you.
Casting down and instanceof
Sometimes you hold an Animal reference and need a Dog-only method. You can convert the reference with a cast. A cast to a subclass is called a downcast.
Animal a = new Dog();
Dog d = (Dog) a;
d.fetch();This works because the object really is a Dog. If it is not, the program fails at run time with a ClassCastException.
Animal a = new Animal();
Dog d = (Dog) a; // throws ClassCastException when it runsThe compiler allows this code because an Animal variable could hold a Dog. Only the running program can find out that it does not.
To avoid the error, check first with instanceof. It gives true when the object is of that class or a subclass of it.
public class Main {
public static void main(String[] args) {
Animal[] animals = { new Dog(), new Animal() };
for (Animal animal : animals) {
if (animal instanceof Dog) {
Dog dog = (Dog) animal;
dog.fetch();
} else {
System.out.println("Not a dog");
}
}
}
}Java 16 and later lets you combine the test and the cast. This is called pattern matching for instanceof.
if (animal instanceof Dog dog) {
dog.fetch();
}If you find yourself writing many instanceof checks, think about adding a method to the superclass and overriding it instead. Dynamic dispatch is usually cleaner than a chain of type tests.
What dispatch does not apply to
Dynamic dispatch works for instance methods that can be overridden. It does not work for everything. Two cases surprise beginners.
Fields are not polymorphic
A field is looked up using the declared type, not the runtime type.
class Animal {
String label = "animal";
}
class Dog extends Animal {
String label = "dog";
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
System.out.println(a.label); // animal
System.out.println(((Dog) a).label); // dog
}
}Both fields exist inside the object. Which one you see depends on the declared type of the expression. A later chapter covers this, which is called field hiding.
Static methods are not overridden
Static methods belong to a class, not to an object. Java picks the static method using the declared type.
class Animal {
static String kind() {
return "animal";
}
}
class Dog extends Animal {
static String kind() {
return "dog";
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
System.out.println(a.kind()); // animal
}
}This is called static method hiding, not overriding. It is also covered later.
Private methods and final methods also are not overridden, so they have no dynamic choice to make.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Calling a subclass-only method on a superclass variable | Compile error | Downcast after checking with `instanceof` |
| Downcasting without a check | `ClassCastException` at run time | Test with `instanceof` first |
| Expecting a field to follow the object's class | You read the superclass field | Use methods, not fields, for behavior that should vary |
| Expecting a static method to be overridden | The superclass version runs | Use an instance method |
| Changing a method's parameter list and expecting dispatch | The method is a new overload, not an override | Add `@Override` so the compiler catches it |
Summary
- A subclass is a subtype. A
Dogcan be used wherever anAnimalis expected. - The declared type is in the code. The runtime type is the class of the actual object.
- For overridden instance methods, Java uses the runtime type to choose the version. This is dynamic dispatch.
- The declared type controls which members the compiler lets you use.
- Use
instanceofbefore a downcast to avoidClassCastException. - Fields and static methods are chosen by the declared type, not by dispatch.
Exercise
Given these classes, what does the program print, and why? class A { String who() { return "A"; } } class B extends A { String who() { return "B"; } } class C extends B { } public class Main { public static void main(String[] args) { A x = new C(); System.out.println(x.who()); } }
Show answer
It prints "B". The declared type of x is A, so the call who() compiles. The runtime type is C. C does not define who(), so Java looks up the chain and finds B's version first. B's version is more specific than A's, so it runs.
Exercise
Why does the last line below fail to compile, and how can you fix it safely? Animal a = new Dog(); a.fetch();
Show answer
The declared type Animal has no fetch() method, and the compiler checks only the declared type. Fix it by checking and casting: if (a instanceof Dog) { ((Dog) a).fetch(); }, or in Java 16 and later: if (a instanceof Dog d) { d.fetch(); }.
Exercise
Class Animal has a static method kind() returning "animal". Class Dog extends Animal and declares its own static kind() returning "dog". What does Animal a = new Dog(); System.out.println(a.kind()); print? Is this overriding?
Show answer
It prints "animal". Static methods are chosen by the declared type, which is Animal. This is static method hiding, not overriding, so dynamic dispatch does not apply.