INH - Creating References Using Inheritance Hierarchies (Lesson)

APCompSci_LessonTopBanner.png

Creating References Using Inheritance Hierarchies

Introduction

Create an inheritance hierarchy chart with Animal as the parent class. Add several subclasses that would extend the Animal class. Brainstorm what instance variables and methods would be in each class. What would be inherited and what would be added to the subclasses?

Object Declarations

ObjectDeclarations.png Since inheritance uses is-a relationships, it is possible for the superclass to refer to objects in either the superclass or subclasses.

Animal bebe = new Animal ( ) ;

Animal ollie = new Dog ( ) ; 

This works because a Dog is-a Animal. It would be illegal to write Dog ann = new Animal(); because not all Animal objects are Dog objects. Dog is-a Animal is an accurate statement. Animal is-a Dog is an inaccurate statement. (Remember that assignment statements are read right to left so we look at the left part first and say is-a to what is on the right.)

When a class Dog is-a class Animal, Animal is the superclass, and Dog is the subclass. If Dog is a subclass of Animal, then assigning an object of type Dog to a reference of type Animal facilitates polymorphism. More on this in our next lesson.

If Dog is a subclass of Animal, then a reference to type Animal can be used to refer to an object of type Animal or Dog.

This can be especially helpful if we wanted to make an array of type Animal and have all different animal subclass elements (Dog, Kangaroo, etc.).

BookIcon.png READ 5 Steps to a 5:

  • Concept 7

is-a Check Up

Click below to begin the is-a Check Up activity.

 

Practice-It! Practice

PracticeIcon.png Go to the PracticeIt website Links to an external site..

Log into account.

Click on Start Practicing!

Go to the most recent edition.

Click on Chapter 9: Inheritance and Interfaces

Complete Self-Check: 9.8 & 9.10

APCompSci_LessonBottomBanner.pngIMAGES CREATED BY GAVS