CS 46B - Lecture 3

Cover page image

Cay S. Horstmann

Pre-class reading

Plagiarism

Inheritance Basics

Lecture 3 Clicker Question 1

Which of the following statements is true?

  1. BankAccount is a subclass of SavingsAccount
  2. The SavingsAccount method overrides the deposit method of BankAccount
  3. The SavingsAccount method inherits the addInterest method of BankAccount
  4. The SavingsAccount method inherits the getBalance method of CheckingAccount

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

Polymorphic Self Calls

Calling super

Lecture 3 Clicker Question 2

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

Superclass Construction

Lecture 3 Clicker Question 3

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.

Lab

???