Title: Inheritance Introduction
Course: CPS 161: An Intro to Programming with Java - DL MM MASTER

Inheritance Introduction

Classes - give you a way to take a big problem and break it down into smaller well defined pieces

Inheritance - a characteristic of classes that simplifies our life

Example from industry with TIFF files:

Using Code Building Blocks : Graphical User Interfaces

.

"IS A " relationship

The world of living examples is full of the idea of Inheritance -

Using Class Inheritance to provide a better programming structure.

The Game of Chess:

Textbook Example

Book Examples (Employee, Date, HourlyEmployee, SalariedEmployee)

Start with the Book's Employee class, we will put together the HourlyEmployee from scratch to see what is going on.

1. Create an HourlyEmployee class and DemoHourlyEmployee classes.
2. As we add the following features to HourlyEmployee, call the new methods in the DemoHourlyEmployee class.
3. Add private data for HourlyEmployee
4. Add default constructor and a constructor that specifies everything
5. Put print statements into the Constructors and step through the code
6. Provide getters and setters for HourlyEmployee
7. Provide a toString approach 1 (calling getters in Employee)
8. Change toString to use super.toString
9. Provide an equals method approach 1 (calling getters in Employee)
10. Change equals to use super.equals

One last warning is that the compiler really doesn't know when "Is A" is violated. It is up to the programmer to use class inheritance properly.
There is another relationship that might be more appropriate: "Has A". Sometimes this other relationship is referred to as:
Composition. In other words we have one class containing or being composed of another class.

Note that with our Employee class we have a Date class inside of the Employee class.
We would say that an Employee HAS A Date class and this makes sense. We would also say that the relationship between HourlyEmployee and Employee is: "IS A".

However, its really only Humans that understand "IS A" and "HAS A" relationships. The compiler will let you structure classes improperly. For example, suppose that I structure Employee as extending the Date class. Here is the code that actually compiles:

Employee extending Date class

Although the compiler will let me do this, I have implied that an Employee "IS A" Date. Again humans have to use the constructs properly and the Compiler will blindly do whatever it is told.

Last Modified: October 24, 2013 1:53 PM