Sub topic 2
One Variable, Many Kinds of Objects
In the last chapter you made subclasses with extends. A Dog is a kind of Animal, and so is a Cat. This chapter covers what that relationship lets you do with variables. In Java, a variable of type Animal can hold a Dog object, a Cat object, or a plain Animal object. Polymorphism is built on this idea, so it is worth learning well before moving on.
Two Types, Not One
When you write a line like this, two different types are involved:
Animal pet = new Dog();- The declared type is the type written on the left, in the variable's declaration. Here it is
Animal. It never changes for the life of the variable. - The runtime type is the class of the object that was actually built with
new. Here it isDog. It is the real class of the object in memory.
A reference is the value stored in the variable. It points to an object; it is not the object itself. So pet is a reference whose declared type is Animal, and right now it points to an object whose runtime type is Dog.
Upcasting: Storing a Subclass in a Superclass Variable
Upcasting means treating an object as one of its superclass types. A superclass is the class another class extends; Animal is the superclass of Dog. Java upcasts for you automatically. You do not need any special syntax.
Upcasting is always safe because of the "is a" rule. Every Dog is an Animal, so anything you can ask an Animal to do, a Dog can do too.
Here is a complete program you can run. It uses getClass().getSimpleName(), a built-in method that returns the name of an object's runtime class.
class Animal {
void eat() {
System.out.println("This animal is eating");
}
}
class Dog extends Animal {
void fetch() {
System.out.println("The dog fetches the ball");
}
}
class Cat extends Animal {
void purr() {
System.out.println("The cat purrs");
}
}
public class Main {
public static void main(String[] args) {
Animal pet = new Dog(); // upcast: Dog stored as Animal
pet.eat(); // allowed: Animal has eat()
System.out.println(pet.getClass().getSimpleName()); // Dog
pet = new Cat(); // same variable, new object
pet.eat();
System.out.println(pet.getClass().getSimpleName()); // Cat
}
}Output:
This animal is eating
Dog
This animal is eating
CatThe variable pet kept its declared type, Animal, the whole time. Its runtime type changed from Dog to Cat when we gave it a new object.
The Compiler Only Sees the Declared Type
The compiler is the program (javac) that checks your code and turns it into bytecode before it runs. The compiler looks only at the declared type. It does not track which object a variable will hold at runtime.
That is why this does not compile, even though the object really is a Dog:
public class Main {
public static void main(String[] args) {
Animal pet = new Dog();
pet.eat(); // OK: eat() is declared in Animal
// pet.fetch(); // compile error: cannot find symbol fetch()
}
}(This file uses the Animal and Dog classes from the earlier program.) Remove the // before pet.fetch() and the compiler stops with an error. It reasons this way: "pet is an Animal. Animal has no fetch() method. Some animals cannot fetch." The compiler cannot be sure the object is a Dog, so it refuses.
The JVM (Java Virtual Machine) is the program that runs your compiled code. The JVM does know the runtime type of every object. It has to, because it built that object. The two types answer different questions:
| Question | Who answers it | Which type it uses |
|---|---|---|
| Which methods am I allowed to call? | Compiler | Declared type |
| What kind of object is this really? | JVM | Runtime type |
| Which version of a method runs? | JVM | Runtime type (covered in later chapters) |
The third row matters most for the rest of this tutorial. Once subclasses replace inherited methods, the runtime type decides which version runs. The next chapters on overriding and dynamic dispatch explain how.
The Other Direction Is Not Automatic
Upcasting goes from a subclass to a superclass. Going the other way, from Animal to Dog, is called downcasting, and Java will not do it for you:
public class Main {
public static void main(String[] args) {
Animal pet = new Dog();
// Dog d = pet; // compile error: incompatible types
}
}The compiler blocks this because not every Animal is a Dog. The variable could hold a Cat. A later chapter, "Getting the Specific Type Back: Casting and instanceof," shows how to downcast safely.
Why This Is Useful
If a variable could only hold one exact class, you would need separate code for dogs, cats, and every other animal. Upcasting lets you write code once for the superclass and use it with every subclass.
You will see this in three common places:
- Arrays and lists. One array can hold many kinds of animals.
- Method parameters. A method that takes an
Animalaccepts any subclass. - Return types. A method can declare that it returns
Animaland actually return aDog.
class Animal {
void eat() {
System.out.println("Eating");
}
}
class Dog extends Animal { }
class Cat extends Animal { }
public class Main {
// Parameter: declared type Animal, accepts any subclass
static void feed(Animal a) {
System.out.print(a.getClass().getSimpleName() + ": ");
a.eat();
}
// Return type: declared Animal, actually returns a Dog
static Animal adopt() {
return new Dog();
}
public static void main(String[] args) {
Animal[] zoo = { new Dog(), new Cat(), new Animal() };
for (Animal a : zoo) {
feed(a);
}
Animal adopted = adopt();
System.out.println("Adopted a " + adopted.getClass().getSimpleName());
}
}Output:
Dog: Eating
Cat: Eating
Animal: Eating
Adopted a DogThe feed method does not need to know about Dog or Cat. If you add a Rabbit extends Animal class next year, feed works with it without changes.
Edge Cases Worth Knowing
Several variables, one object
Two references can point to the same object with different declared types:
Dog rex = new Dog();
Animal sameRex = rex; // upcast, no copy is madeBoth rex and sameRex point to one object. Through rex you may call fetch(). Through sameRex you may not. The object did not change. Only the view of it did.
null has no runtime type
A variable can hold null, which means it points to no object. There is no runtime type then. Calling pet.getClass() when pet is null throws a NullPointerException.
Object sits at the top
Every class in Java extends Object, directly or indirectly. So this always compiles:
Object thing = new Dog();With declared type Object, the compiler only lets you call methods that Object has, such as toString() and getClass().
var copies the type from the right side
The var keyword (Java 10 and later) lets the compiler choose the declared type for you. It uses the type of the expression on the right:
var d = new Dog(); // declared type is Dog, not Animal
d.fetch(); // allowedIf you want an Animal variable, write Animal yourself.
The declared type limits reassignment
A variable declared as Dog can only point to a Dog or a subclass of Dog. You cannot put a Cat in it. A wider declared type, like Animal, accepts more kinds of objects, but you can call fewer methods through it.
Common Mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Calling a subclass-only method through a superclass variable | Compile error: cannot find symbol | Declare the variable with the subclass type, or downcast safely (later chapter) |
| Assigning a superclass variable to a subclass variable | Compile error: incompatible types | Use a checked downcast (later chapter) |
| Thinking upcasting copies or converts the object | Confusion about which object you have | Remember that upcasting changes only the view; the object is unchanged |
| Calling methods on a `null` reference | `NullPointerException` at runtime | Check for `null` before using the variable |
Summary
- A variable has a declared type. The object it points to has a runtime type.
- Upcasting stores a subclass object in a superclass variable. It is automatic and safe.
- The compiler uses the declared type to decide which methods you may call.
- The JVM knows the runtime type, and later chapters show how it uses that type to pick which method version runs.
- Downcasting is not automatic and needs a check.
Exercise
Given Animal a = new Cat();, what is the declared type of a, what is its runtime type, and what does System.out.println(a.getClass().getSimpleName()); print?
Show answer
The declared type is Animal and the runtime type is Cat. The line prints "Cat", because getClass() reports the class of the actual object.
Exercise
Using the Animal, Dog, and Cat classes from this chapter, which of these lines compile? (1) Animal x = new Dog(); (2) Dog y = new Animal(); (3) Animal z = new Cat(); z.purr(); (4) Object o = new Cat();
Show answer
Lines 1 and 4 compile. Line 1 is an upcast from Dog to Animal, and line 4 is an upcast to Object. Line 2 fails because an Animal is not necessarily a Dog. Line 3 fails because purr() is not declared in Animal, and the compiler only checks the declared type.
Exercise
Write a method static void describe(Animal a) that prints "This is a " followed by the runtime class name. Call it with a Dog and with a Cat.
Show answer
static void describe(Animal a) { System.out.println("This is a " + a.getClass().getSimpleName()); } Calling describe(new Dog()) prints "This is a Dog" and describe(new Cat()) prints "This is a Cat". Both calls compile because each argument is upcast to Animal automatically.