08 Inheritance Polymorphism
08 Inheritance Polymorphism
08 Inheritance Polymorphism
Inheritance and
Polymorphism A class contains another class if it instantiates an
object of that class
This can be described as a “HAS-A” relationship
CSE 114: Computer Science I
Course HAS-A Professor
Stony Brook University
CAR HAS-A Engine
Is a mammal Is a mammal
Some classes share properties that are similar
Has fur Has fur
For example, cats and dogs are both mammals and
Common house pet Common house pet common house pets
Has several breeds Has several breeds It doesn’t make sense to duplicate shared
properties unnecessarily (remember the DRY
principle we discussed previously)
Meows Barks
Scratches the furniture Catches Frisbees Instead, we can abstract out common
characteristics
Catches mice Chases squirrels
10
// instance variables for Child only public class Cat extends Mammal
{
// methods for Child only boolean hasClaws;
String furColor;
} public void makeSound()
{
ChildClass now contains all instance variables and System.out.println(“Meow!”);
methods defined above, as well as those defined inside }
ParentClass }
ILLEGAL LEGAL
• private methods of a base class are not accessible by
the derived class. 22
Person
• A class may have any Cletus Mary
number of ancestors; Joe
getAge() : int
Container getName() : String
setAge(newAge: int) : void
Triangle denotes inheritance
JComponent Window
Student IS-A Person
Student
JPanel AbstractButton Frame
gpa: double
getGPA() : double
JFrame setGPA(newGPA: double) : void
JButton
OOP Characteristics
Assignment
43
Assignment Method Invocation
Suppose that Mammal and Cat each define a
We CANNOT go the other way, though! method named makeSound()
Cat c = new Mammal(); // Illegal Cat’s version overrides Mammal’s version
c expects to point to an object with all of Cat’s Which version of makeSound() will be called in
features each of the following cases?
There is no guarantee that a Mammal object has 1. Mammal m = new Mammal();
all of those features m.makeSound();
In fact, it probably doesn’t 2. Mammal x = new Cat();
x.makeSound();