CS 46B - Lecture 2

Cover page image

Cay S. Horstmann

Pre-class reading

Inheritance Basics

Common Error: Shadowing Instance Variables

Common Error: Shadowing Instance variables

Now the addInterest method compiles, but it doesn't update the correct balance!

Overriding Methods

Overriding Methods

Polymorphism

Common Error: Accidental Overloading

Lecture 2 Clicker Question 1

Suppose we define

public class CheckingAccount extends BankAccount
{
   public void withdraw(double amount, String purpose)
   {
      super.withdraw(amount);
      System.out.printf("Withdrawing $%.2f for %s\n", amount, purpose);
   }
}

What does this code snippet print?

BankAccount b = new CheckingAccount();
b.deposit(1000);
b.withdraw(100, "cell phone");
  1. Withdrawing $100.00 for cell phone
  2. Balance: $900.00
  3. The code snippet compiles and prints nothing
  4. The code snippet does not compile

Calling super

Superclass Construction

Syntax 9.3 Constructor with Superclass Initializer

supper class initializer of constructor

Lecture 2 Clicker Question 2

Why does the deposit method of the CheckingAccount class call super.deposit?

  1. It needs to invoke the superclass constructor
  2. Whenever you override a method, you must call super in order to avoid recursion
  3. Every method that overrides another method must have a call to super as the first statement
  4. It needs to update the balance, and it cannot access the balance variable directly.

Polymorphic Self Calls

Lecture 2 Clicker Question 3

class A { 
   void print(String s) { System.out.print(s); }
   void f() { print("f"); g(); } 
   void g() { print("g"); }
}
class B extends A {
   void f() { print("f"); super.f(); }
   void g() { h(); }
   void h() { print("h"); }
}

A a = new B(); 
a.f(); // What does it print?
  1. fg
  2. ffg
  3. ffh
  4. None of the above

Object: The Cosmic Superclass

Overriding the toString Method

toString and Inheritance

Lecture 2 Clicker Question 4

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 2 Clicker Question 5

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

Before Next Class