Lecture 14: Objects and Lists

Overview

  1. Object Inheritance
  2. Representing Lists of Objects

Last Time

  • Casting objects as other types
  • Class hierarchies
  • The Object class
    • every class is a subclass of Object

Why is Object Inheritance Good?

Object has the following methods (among others):

  • boolean equals(Object obj)
  • String toString()

Therefore, every class in Java has these methods

Testing Methods with Animal

Animal a = new Elephant("Alice");
Animal b = new Elephant("Alice");

What is the behavior of…

  • a.equals(b)?
  • a.toString()?

Let’s see!

Overriding Default Behavior

  • default a.equals(b) is equivalent to a == b
  • default a.toString() prints address (not meaningful)

How should we…

  • … check equality of Animals?
  • … represent an Animal as a String?