CS 46B - Lecture 4

Cover page image

Cay S. Horstmann

Pre-class reading

Converting Between Subclass and Superclass Types

Converting Between Subclass and Superclass Types

Converting Between Subclass and Superclass Types

Lecture 4 Clicker Question 1

Why was the second parameter of the transfer method of type BankAccount?

public void transfer(double amount, BankAccount other)
{
   withdraw(amount);
   other.deposit(amount);
}
  1. That's an error—it should have been of type SavingsAccount
  2. That's an error—it should have been of type Object
  3. So that the method can be called with SavingsAccount and CheckingAccount objects
  4. So that the method can be called with objects of any subclass of BankAccount

Object: The Cosmic Superclass

Overriding the toString Method

toString and Inheritance

Lecture 4 Clicker Question 2

BankAccount acct = new SavingsAccount(0.5);
System.out.println(acct);

What does it print?

  1. BankAccount[balance=0.0]
  2. SavingsAccount[balance=0.0]
  3. SavingsAccount[balance=0.0, interestRate=0.5]
  4. SavingsAccount[balance=0.0][interestRate=0.5]

Overriding the equals Method

Overriding the equals Method

Lecture 4 Clicker Question 3

public class CollectibleCoin extends Coin
{
   . . .
   public boolean equals(Object otherObject)
   {
      CollectibleCoin other = (CollectibleCoin) otherObject;
      return getName().equals(other.getName()) && getValue == other.getValue()
         && year == other.getYear;
   }
}

Coin c1 = new Coin("quarter", 0.25);
Coin c2 = new CollectibleCoin("quarter", 0.25, 1993);

What do c1.equals(c2) and c2.equals(c1) return?

  1. Both return true
  2. Both return false
  3. The first one returns true, the second one returns false
  4. The first one returns true, the second one throws an exception

Equals and Inheritance

Lab

???