Inheritance

10.5 - 10.7

Using a superclass reference

Converting Between Subclass and Superclass

Converting Between Subclass and Superclass

Converting Between Subclass and Superclass

Often useful in processing different subclasses of a superclass

public void transfer(double amount, BankAccount other)
{
   withdraw(amount);
   other.deposit(amount);
}

Class 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

Follow-up Question

Why can't we change the second parameter of the transfer method to the type Object?

Getting a subclass reference

Getting a subclass reference

The mother of all classes: Object

Look at Object in the Java API

http://docs.oracle.com/javase/7/docs/api/

 

Object's methods

The toString method*

Override the toString method

A better toString

A better toString

Objects equals method*

Overriding equals

Overriding equals in Coin class

public class Coin
{
   . . .
   public boolean equals(Object otherObject)
   {
      Coin other = (Coin) otherObject;
      return name.equals(other.name) 
         && value == other.value;
   }
}

Overriding equals

Overriding equals

Class question #2

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

Fixing the problem

But that is not logical.

To fix the problem, equals should test that objects are of the same class

Abstract classes

Special topic 10.1

Animal Class Example

Abstract Method

AbstractAnimal

By convention, abstract class usually start withthe word abstract in Java

public abstract class AbstractAnimal
{ private int averageLifeSpan; public AbstractAnimal(int span) {averageLifeSpan = span; } public int getAverageLifeSpan() {return averageLifeSpan; } public abstract String eats(); }

 

Concrete subclass

public class Cat
{
   public Cat(int span)
   {
      super(span);
   }
   
   public String eats()
   {
      return "mice";
   }
}

Abstract vs Concrete class

Abstract class vs interface

More about Java.