COMP 121 Week 3

Download Report

Transcript COMP 121 Week 3

COMP 121
Week 3:
Inheritance
Objectives
To learn about inheritance
 To understand how to inherit and override
superclass methods
 To be able to invoke superclass
constructors
 To understand the common superclass
Object and to override its toString
method

Introduction to Inheritance

Inheritance
 Used
with object types that have a certain amount
of commonality





Mountain bikes, racing bikes, road bikes, and recumbent
bikes all share characteristics common to bicycles
Squares, triangles, rectangles, and octagons all share
characteristics common to polygons
Deans, professors, administrators, and technical support
personnel all share characteristics common to university
employees
Surgeons, family doctors, pediatricians, heart specialists all
share characteristics common to doctors
Savings accounts, checking accounts, money market
accounts all share characteristics common to bank accounts
Introduction to Inheritance

Inheritance relationship
 Mountain
bike inherits from bicycle
 Triangle inherits from polygon
 Professor inherits from university employee
 Pediatrician inherits from doctor
 Savings account inherits from bank account

Classes are extended by adding methods and
fields
 Savings


account is a bank account with interest
Instance field would be added for the interest rate
Method would be added to add interest to the account
Inheritance vs. Implementing an
Interface

Inheriting from class is not the same as
implementing an interface
 Subclass

inherits behavior and state
Like interfaces, one advantage of
inheritance is code reuse
Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Inheritance Diagram

Every class extends the
Object class either directly or
indirectly
Inheritance
Inheritance
Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Inheritance Diagram (BlueJ)
Inheritance
UML Diagram (BlueJ)
Uses
Is-A
Inheritance
Inheritance Syntax
class SubclassName extends SuperclassName
{
methods
instance fields
}
The extended class is called the
superclass
 The extending class is called the subclass

Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Question:

If the class Car extends Vehicle, which is
the subclass and which is the superclass?
Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Subclass versus Superclass
Superclass
Subclass
Inheritance Example
public class SavingsAccount extends BankAccount
{
// Fields and methods unique to a SavingsAccount
…
}



BankAccount is the superclass
SavingsAccount is the subclass
SavingsAccount automatically inherits all
methods and instance fields of BankAccount
Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Subclass Fields and Methods

In subclass:
 Add
new instance fields and methods
 Change or override methods
public class SavingsAccount extends BankAccount
{
public SavingsAccount(double rate)
{
interestRate = rate;
}
public void addInterest()
{
double interest = getBalance() * interestRate / 100;
deposit(interest);
}
private double interestRate;
}
Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Subclass Object
SavingsAccount object inherits the
balance instance field from BankAccount
 Additional instance field is interestRate

Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Encapsulation and Inheritance
public void addInterest()
{
double interest = getBalance() * interestRate / 100;
deposit(interest);
}

Encapsulation
 addInterest
calls getBalance rather than
updating the balance field of the superclass (field is
private)
 addInterest calls getBalance without specifying
the implicit parameter

Call applies to the same object (this)
Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Inheritance Hierarchies

Sets of classes can form complex
inheritance hierarchies
Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Inheritance Hierarchies: Swing
Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Hierarchy of Bank Accounts

Consider a bank that offers its customers
the following account types:
Checking account: no interest; small number
of free transactions per month, additional
transactions are charged a small fee
2. Savings account: earns interest that
compounds monthly
1.
Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Hierarchy of Bank Accounts
Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Hierarchy of Bank Accounts
Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Subclass vs. Superclass Methods
All bank accounts support the
getBalance method
 All bank accounts support the deposit
and withdraw methods, but the
implementations differ (checking account
needs to count transactions)
 Checking account needs a method
deductFees
 Savings account needs a method
addInterest

Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Overriding vs. Inheriting Methods

Overriding a method
 Supply
a different implementation of a method
that exists in the superclass
 Must have same signature (same name and
same parameter types)
 If method is called on an object of the
subclass type, the overriding method is
executed
Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Overriding vs. Inheriting Methods

Inheriting a method (behavior)
 Don't
supply a new implementation of a
method that exists in superclass
 Superclass method can be called on the
subclass objects
Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Defining New Methods

Add a method
 Supply
a new method that doesn't exist in the
superclass
 New method can be called only on subclass
objects
Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Inheriting Instance Fields
Can't override fields
 All fields from the superclass are
automatically inherited
 New fields that don't exist in the
superclass can be added to the subclass

Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Inheriting Instance Fields

What if you define a new field with the
same name as a superclass field?
 Each
object would have two instance fields of
the same name
 Fields can hold different values
 Legal but extremely undesirable
 DON’T DO IT!!!
Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
CheckingAccount Implementation

Overrides deposit and withdraw to
increment the transaction count
public class CheckingAccount extends BankAccount
{
public void deposit(double amount) {. . .}
public void withdraw(double amount) {. . .}
public void deductFees() {. . .} // new method
private int transactionCount;
// new instance field
}
Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
CheckingAccount Implementation

Each CheckingAccount object has two
instance fields:
 balance
(inherited from BankAccount)
 transactionCount (new to
CheckingAccount)
Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
CheckingAccount Implementation

You can apply four methods to
CheckingAccount objects:
 getBalance()
(inherited from BankAccount)
 deposit(double amount) (overrides
BankAccount method)
 withdraw(double amount) (overrides
BankAccount method)
 deductFees() (new to CheckingAccount)
Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Accessing Private Fields in Superclass

Consider deposit method of
CheckingAccount
public void deposit(double amount)
{
transactionCount++;
// now add amount to balance
. . .
}


Can't just add amount to balance
balance is a private field of the superclass
Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Accessing Private Fields in Superclass
A subclass has no access to private fields of
its superclass
 Subclass must use public interface

So how can we add the amount to the balance?
Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Invoking a Super Class Method

Can't just call
deposit(amount)in deposit method
of CheckingAccount

That is the same as
this.deposit(amount)
Calls the same method (infinite loop)
 Instead, invoke superclass method
super.deposit(amount)

Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Invoking a Superclass Method
public void deposit(double amount)
{
// Increment the transaction count
transactionCount++;
// Now add amount to balance
super.deposit(amount);
}
Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Subclass Construction




The super keyword is also used to call a
constructor
super followed by parameters in parentheses
indicates a call to the superclass constructor
Must be the first statement in subclass constructor
If subclass constructor doesn't explicitly call
superclass constructor, the default superclass
constructor is used
 Default
constructor -- constructor with no parameters
 If all superclass constructors require parameters, it’s a
compile error error
Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Subclass Construction
public class CheckingAccount extends BankAccount
{
public CheckingAccount(double initialBalance)
{
// Construct superclass
super(initialBalance);
// Initialize transaction count
transactionCount = 0;
}
. . .
}
Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Converting Between Subclass
and Superclass Types

Can convert a subclass reference to
superclass reference
SavingsAccount collegeFund = new SavingsAccount(10);
BankAccount anAccount = collegeFund;
Object anObject = collegeFund;

The three object references stored in
collegeFund, anAccount, and anObject
all refer to the same object of type
SavingsAccount
Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Converting Between Subclass
and Superclass Types
Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Converting Between Subclass
and Superclass Types

Superclass references don't know about
methods in the subclass
anAccount.deposit(1000); // OK
anAccount.addInterest(); // Not OK

When you convert a subclass object to its
superclass type
 The
value of the reference stays the same
(actual memory location of the object)
 Less information is known about the object
Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Converting Between Subclass
and Superclass Types

Why would anyone want to know less
about an object?
 Reuse
code that knows about the superclass
publicbut
void
nottransfer(double
the subclass: amount, BankAccount other)
{
withdraw(amount);
other.deposit(amount);
}

Can be used to transfer money from any
type of BankAccount
Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Converting Between Subclass
and Superclass Types

Occasionally you need to convert from a
superclass reference to a subclass
reference
BankAccount anAccount = (BankAccount) anObject;

If object types are unrelated (not a
superclass/ subclass relationship), an
exception is thrown at runtime
Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
instanceof operator



Tests whether an object belongs to a particular
type
Returns true if the object on the left hand side of
the operator is an instance of the type on the
right hand side of the operator
Otherwise, returns false
if (anObject instanceof BankAccount)
{
BankAccount anAccount = (BankAccount) anObject;
. . .
}
Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Object: The Cosmic Superclass

All classes defined without an explicit
extends clause automatically extend
Object
Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Useful Methods in the Object Class




String toString()
boolean equals(Object otherObject)
Object clone()
Good idea to override these methods in
your classes

Will not be overriding clone() in this course
Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Overriding the toString Method
Returns a string representation of the
object
 Useful for debugging

Rectangle box = new Rectangle(5, 10, 20, 30);
String s = box.toString();
// Sets s to "java.awt.Rectangle[x=5,y=10,width=20,height=30]"
Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Overriding the toString Method

toString is called whenever you
concatenate a string with an object:
"box=" + box;
// Result: "box=java.awt.Rectangle[x=5,y=10,width=20,height=30]"

Object.toString default behavior is to
print the class name and the hash code of
the object
BankAccount momsSavings = new BankAccount(5000);
String s = momsSavings.toString();
// Sets s to something like "BankAccount@d24606bf"
Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Overriding the toString Method

In BankAccount:
public String toString()
{
return "BankAccount[balance=" + balance + "]";
}

Converts BankAccount object to a String
BankAccount momsSavings = new BankAccount(5000);
String s = momsSavings.toString();
// Sets s to "BankAccount[balance=5000]"

Used by System.out.println
Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Inheritance and toString Method



toString method often returns the
class name and the names and values of
the instance fields in a class
In a superclass, to be usable by
subclasses, get the class name instead of
hard-coding it
For example, in BankAccount:
public String toString()
{
return getClass().getName()+" [balance =" + balance + "]";
}
Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Inheritance and toString Method


In a subclass, first get the string that
represents the superclass, then add the
subclass information
For example, in SavingsAccount:
public String toString()
{
return super.toString() +
" [interestRate = " + interestRate + "]";
}
Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Summary
Inheritance is used to extend existing
classes by adding methods and fields
 The more general class is called the
superclass
 The more specialized class that inherits
from the superclass is called the subclass
 The subclass inherits both state and
behavior from the superclass
 Code reuse is one advantage of
inheritance

Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Summary (continued)
Methods in the superclass can be
changed or overridden in the subclass
 A subclass cannot access the private
fields of the superclass
 The super keyword is used to call a
method of the superclass
 The super keyword may also be used as
the first statement of the subclass
constructor to call the superclass
constructor

Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Summary (continued)
The instanceof operator tests whether
an object belongs to a particular type
 The toString method should be
overridden to return a String that
represents the object’s state

Horstmann, C. (2008). Big Java (3rd ed.). New York: John Wiley & Sons.
Any Questions?