Renato Osses Carrizo - Worksheet - CodeHS - Inheritance and Polymorphism
Renato Osses Carrizo - Worksheet - CodeHS - Inheritance and Polymorphism
Corresponding Material
Inheritance, Polymorphism
Discussion
The topics of inheritance and polymorphism are closely related. Polymorphism is
only possible because classes are able to inherit from another class. What kind of
relationship do child classes have with their parent classes? (child IS-A parent, like
a lake IS-A body of water or a cat IS-A mammal). What parts of the parent class
do child classes inherit? (public and protected methods, NOT the constructor)
We can see that child classes and parent classes are very closely related. Just like
a child shares certain traits with his/her biological parents, a child class has certain
traits in common with its parent class. However, like human children are unique
people with traits that differ from their parents, child classes can also have different
traits.
For example, let’s say Emily is a 3-year-old child of Liam. Liam has brown hair, and
so does Emily. Liam lives in Huddersfield, and so does Emily. Liam has a dresser
full of clothes, and so does Emily. However, Liam’s drawers are filled with adult’s
clothes, while Emily’s drawers are filled with toddler’s clothes.
Now let’s think of Liam and Emily as Java classes. Let’s say that Liam has the type
Guardian, and Emily has the type Infant. Thus, the classes we have are Guardian
and Infant, where Infant and Guardian inherit from the class FamilyMember.
Furthermore, let’s say that Guardian, Infant, and FamilyMember have the following
variables and methods (in addition to others that are not listed).
Note that both child classes have overridden the chooseClothes method.
Liam.getHometown() and Emily.getHometown() would both return “Huddersfield”,
since they both live in the same house in the same town. However,
Liam.chooseClothes() would return adult’s clothes, since his drawer is filled with
adult’s clothes. Emily.chooseClothes() would return toddler’s clothes since her
drawer is filled with toddler’s clothes.
Class Exercise
Suppose you have a base class named Clothes. The classes Jeans, Shirt, and Socks
all inherit from Clothes. The methods and variables defined in each class are listed
below.
Variables: Methods:
color getNeckType
materialType
size
Methods:
getColor
getMaterial
getSize
Methods: Variables:
getNumberOfPockets smells
Methods:
areSmelly
Given these definitions, which of the following numbered lines of code are illegal?
Why?
1. top.getColor();
2. bottom.getNeckType();
3. Socks gymSocks = new Clothes(“white”, “silk”, “M”);
4. Clothes dressShirt = new Shirt(“blue”, “spandex”, “XL”);
5. Clothes scarf = new Clothes(“flannel”, “wool”, “S”);
6. footwear.areSmelly()
7. Clothes extraSocks = footwear;
8. Shirt golfShirt = scarf;