10.7 Inheritance: Base Classes and Subclasses

  • Often, an object of one class is an object of another class as well
  • a CarLoan is a Loan as are HomeImprovementLoans and MortgageLoans
  • Class CarLoan can be said to inherit from class Loan.
  • In this context, class Loan is a base class, and class CarLoan is a subclass
  • A CarLoan is a specific type of Loan, but it’s incorrect to claim that every Loan is a CarLoan

10.7 Inheritance: Base Classes and Subclasses (cont.)

  • Table of base classes and subclasses—base classes tend to be “more general” and subclasses “more specific”:
Base class Subclasses
Student GraduateStudent, UndergraduateStuden
Shape Circle, Triangle, Rectangle, Sphere, Cube
Loan CarLoan, HomeImprovementLoan, MortgageLoan
Employee Faculty, Staff
BankAccount CheckingAccount, SavingsAccount

10.7 Inheritance: Base Classes and Subclasses (cont.)

  • Every subclass object is an object of its base class
  • The set of objects represented by a base class is often larger than the set of objects represented by any of its subclasses

CommunityMember Inheritance Hierarchy

  • Inheritance relationships form tree-like hierarchical structures
  • A base class exists in a hierarchical relationship with its subclasses
  • With single inheritance, a class is derived from one base class
  • With multiple inheritance, a subclass inherits from two or more base classes
  • Sample class hierarchy, also called an inheritance hierarchy for a university community

Sample class hierarchy for a university community

  • Each arrow in the hierarchy represents an is-a relationship
    • “an Employee is a CommunityMember
    • “a Teacher is a Faculty member”
  • CommunityMember is the direct base class of Employee, Student and Alum and is an indirect base class of all the other classes in the diagram Starting from the bottom, you can follow the arrows and apply the is-a relationship up to the topmost superclass

Shape Inheritance Hierarchy

Shape inheritance hierarchy

“is a” vs. “has a”

  • Inheritance produces “is-a” relationships in which an object of a subclass type may also be treated as an object of the base-class type
  • In “has-a” (composition) relationships, a class has references to one or more objects of other classes as members