From charlesreid1

Chapter 9: Inheritance and Interfaces

Sections:

9.1 Inheritance basics

9.2 Interacting with the superclass

9.3 Polymorphism

9.4 Inheritance and Design

9.5 Interfaces

9.6 Case study: Financial class hierarchy

Section 9.1: Inheritance Basics

9.1 Definitions

Definitions:

  • Code reuse
  • Is-a relationship
  • Inheritance hierarchy
  • Inheritance (inherit)
  • Superclass
  • Subclass
  • Override

9.1 Material

Large programs on large scale require abstractions - or, another way to look at it, abstractions open up whole new problem spaces

Hierarchy of employees example:

  • Legal firm: lawyers, general secretaries, legal secretaries, marketers
  • Each person is an employee
  • Each X is a Y, &c.
  • Types of employees have salaries, skills, etc., some are new methods, some override parent methods
  • Is-a relationship between classes

Extending a class:

  • Turn non-code example into code
  • Employee class, Secretary class

Overriding methods:

  • Lawyers, vacation days and vacation forms
  • Overloading - re-defining a method from a parent class
  • Overriding - one class with multiple versions of the same method for different parameter signatures

Section 9.2: Interacting with the Superclass

9.2 Material

Calling overridden methods:

  • giving employees a raise: explicitly calling super method
  • can only call super once - super.super.method() not allowed

Accessing inherited fields

  • more complex example than employee class: stocks class
  • encapsulation: even child classes can't examine private data
  • implement an accessor method getParam()
  • Now the child class can define a method that uses a parameter defined in the parent class

Super class constructor

  • Methods are inherited
  • Constructors are NOT inherited
  • can cause trouble when trying to access private data

Example code from book: constructor that sets various fields to initial values

  • Does not compile - fields are all private, cannot be accessed/modified by child class
  • Let's examine what the compiler is REALLY saying:
  • "Wait a minute, what do you think you're doing setting shares and costs? You're a dividend stock - so you take care of dividends. Let the stock class take care of stock stuff, like shares and costs. Mmmkay, thanks."
  • The real solution: let the parent class take care of what it takes care of, let the child class take care of what it takes care of
  • Call the super constructor
  • Finished code for example constructor

DividendStock Behavior

  • implement dividend payments method
  • new method simply computes profit same as old method, plus dividends
  • Extend getProfit(), which calculates the profit using super.getProfit()

Object class

  • superclass for all other Java classes
  • implements few key behaviors: clone(), equals(obj), finalize(), getClass(), hashCode(), toString(), notify()/notifyAll()/wait()
  • can pass as type for a method or constructor parameter, then deal with any input type (although limited in methods can call)

Objects and equality

  • Lamp analogy: if I show you two objects, say a pair of lamps, and I ask you, are these two lamps equal?
  • You might ask me: in what sense?
    • Brightness? Power consumption?
    • Manufacturer, components, parts interchangeable?
    • Exact replica, atom-by-atom, of the original lamp?
    • Cosmic Zen and oneness with the universe: these two lamps are equal only if they are composed of those exact atoms
    • What if one of them is a picture? What if both of them are pictures?

The equals method

  • shoes analogy - equivalent, but distinct and separate items
  • When comparing two objects, we may want to know if they refer to the same location in memory, where data for an object is located
  • Or, we may have two objects referring to different locations in memory, but containing the same values for each variable
  • We have to be clear/specific!
  • The == operator is ambiguous for objects
  • Always, always, always use .equals()
  • Can now use boolean zen: return (a==b) && (c==d)

Checking class/type with instanceof operator

  • We may want to pass arbitrary objects into .equals()
  • However, if we call anything other than generic methods defined for all Object objects, we'll get compiler errors
  • Really need to cast the arbitrary object into a Point first
  • Let's first deal with objects that can be cast as Points
  • Point other = (Point) o;
  • Using instanceof keyword: allows us to use logic like "if can be cast to a Point object, do A, else do B"

Section 9.3: Polymorphism

9.3 Definitions

Definitions:

  • Polymorphism - the ability for the same code to be used with several different types of objects, and for code to behave differently depending on the actual type

9.3 Material

Polymorphism

  • The type of a reference variable does not need to match the type of the object it refers to
  • Specifically, can use superclass references to refer to subclass objects

Polymorphism mechanics

Interpreting inheritance code

Interpreting complex calls

  • Method output tables, tracing complex logic of functions/objects with very generic names

Section 9.4: Inheritance and Design

9.4 Definitions

Definitions:

  • Substitutability
  • Has-a relationship

9.4 Material

A misuse of inheritance

  • Point3D vs Point

Is-a versus Has-a relationships

  • Circle has a point

Examples of different inheritance relationships:

  • Vehicle and Chevy Tahoe objects (parent class is "simpler", fewer details)
  • Polynomials and Lines objects (parent class is "more complicated", more details)
  • Point and Point3D objects (no extendable relationship)

In the first two cases, parent class is the more general class, while the child class is a special case

Section 9.5: Interfaces

9.5 Definitions

Definitions:

  • Interface
  • Abstract method

9.5 Material

Interfaces:

  • What if inheritance is not the right tool for the job?
  • cannot do multiple is-a relationships for classes that share multiple characteristics
  • C++ allows for multiple inheritance: but this raises all kinds of very subtle questions, so subtle sometimes you can't quite describe them, and so inheritance becomes more complicated
  • Java defines interfaces to represent common supertype
  • Classes implement interfaces
  • Interfaces define methods that each class extending that interface must define

An interface for shapes

  • Rectangle, Circle, Triangle objects
  • Polymorphic hierarchy of shape classes - but no code-sharing, because inheritance/code-sharing relationship not appropriate in this case
  • This is a higher-level abstraction
  • We want to define some similarities at a higher level - i.e., not saying, these classes will share these individual fields and methods, and these chunks of code
  • Rather, we're saying, these classes will have these actions/accessors/methods
  • Ludwig Wittgenstein tie-in: meaning and intention are important, get those straight before implementing code; interfaces can help

Implementation of shapes

  • Actual implementation of Rectangle, Circle, Triangle objects
  • getPerimeter() and getArea() methods

UML diagrams:

  • Shape interface
  • Circle, Rectangle, Triangle -------- Shape

Java API: PrintStream class

public class PrintStream extends FilterOutputStream implements Appendable, Closeable

Section 9.6: Financial Class Hierarchy

9.6 Definitions

Definitions:

  • Object-oriented design
  • Refactoring
  • Abstract class

9.6 Material

Design of an object-oriented system

Designing the classes

Redundant implementation

Abstract classes

Chapter 9 Summary

Deliverables

Inheritance concept

  • Translating relationships into inheritance
  • Precedence, order, overriding

Superclass

  • Constructor
  • Overriding
  • Master super class: Object
  • Equality
  • Casting

Polymorphism

  • Overriding
  • Mechanics of inheriting code
  • Interpreting complex calls
  • Method of output tables for tracing complex logic

Inheritance and design

  • How to know when to extend a class
  • Three Examples

Interfaces

  • More advanced topic, getting at TEMPLATING
  • Mention template feature in other languages,
  • Not in Python because of Duck Typing

Chapter 9 Homework

HW Questions

(Recommended) Self-check problems: #5, #6, #7, #9, #12, #14, #19, #20, #23, #24

(Required) Exercises: #4, #9, #15

(Required) Projects: (none - Turtles worksheet will be pretty involved)

HW Details

Self-check:

  • 5 - super vs this
  • 6, 7 - interacting with super class
  • 9 - inheritance example
  • 12, 14 - define classes, create array of objects, what is output
  • 19, 20 - inheritance and design
  • 23, 24 - proper implementation of interfaces

Exercises:

  • 4 - writing a subclass with simple superclass example
  • 9 - bank account example, remembering min/max
  • 15 - octagon, defined by side length, define perimeter and area methods

Chapter 9 Code

Lecture Code

Employee - inheritance code

  • Simple inheritance template

Fly - inheritance code:

  • Subfly and Superfly
  • Fly Driver
  • Another simple inheritance template

FooBarBazMumble - polymorphism code:

  • Illustrates polymorphism with multiple class types
  • Class diagram, several layers to inheritance
  • Overriding select methods for parent class, asking "what will this print"

MakesNoise - interface example

  • Loudspeakers, farm animals, city buses
  • Java scientists engineers - section 7.5

Worksheet Code

Turtle and SpiralTurtule: Inheritance, new methods

  • Nice project - graphical, so helps introduce some graphical elements
  • Introduces them to using someone else's library and documentation for it
  • Introduces them to the usual use case of extension - using someone else's classes
  • Worksheet will be more detailed, less homework from book

Chapter 9 Goodies

Puzzle 2

more Caesar cipher cryptograms, no spaces (frequency or brute force)

Puzzles/Crypto Level 2/Puzzle 2

Profiles

Ludwig Wittgenstein

  • Quotes/excerpts, philosophy of computer programming
  • Think about these concepts as broader language/grammar problems
  • This is why we call them COMPUTER LANGUAGES!

Flags