Java Reference
In-Depth Information
System.out.println(“Cat is breathing”);
}
public void sleep() {
System.out.println(“Cat is sleeping”);
}
}
The is-a relationship is helpful when trying to understand polymorphism. Because Cat
extends Pet , a Cat object is a Pet object. Because Cat implements Mammal , a Cat object is
also a Mammal object. Therefore, the following statements are valid:
Cat c = new Cat(“Garfield”, 3);
Pet p = c;
Mammal m = c;
The reference p can only refer to Pet objects, but because a Cat object is a Pet object,
assigning p to c is valid. Similarly, the reference m can only refer to Mammal objects, but
because a Cat object is a Mammal , assigning m to c is also valid. As Figure 6.5 shows, there
is only one Cat object in memory, but the object is taking on three different forms. The c
reference is treating the object as a Cat , the p reference is treating the object as a Pet , and
the m reference is treating the object as a Mammal .
FIGURE 6.5 The single Cat object takes on different forms.
Cat object
Cat reference
c
name
“Garfield”
age
3
Pet reference
p
sleep()
breathe()
eat()
Mammal
reference
m
Search WWH ::




Custom Search