SlideShare a Scribd company logo
1 of 82
Chapter 10 – Inheritance
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Chapter Goals
• To learn about inheritance
• To understand how to inherit and override superclass methods
• To be able to invoke superclass constructors
• To learn about protected and package access control
• To understand the common superclass Object and to override
its toString and equals methods
G To use inheritance for customizing user interfaces

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Inheritance Hierarchies
• Often categorize concepts into hierarchies:

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Inheritance Hierarchies
• Set of classes can form an inheritance hierarchy
• Classes representing the most general concepts are near the root, more
specialized classes towards the branches:

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Inheritance Hierarchies
• Superclass: more general class
• Subclass: more specialized class that inherits from the
superclass
• Example: JPanel is a subclass of JComponent

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Inheritance Hierarchies
• Example: Different account types:
1. Checking account:
•No interest
•Small number of free transactions per month
•Charges transaction fee for additional transactions
2. Savings account:
•Earns interest that compounds monthly

• Superclass: BankAccount
• Subclasses: CheckingAccount & SavingsAccount

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Inheritance Hierarchies
• Behavior of account classes:
•

All support getBalance method

•

Also support deposit and withdraw methods, but implementation
details differ

•

Checking account needs a method deductFees to deduct the monthly
fees and to reset the transaction counter

•

Checking account must override deposit and withdraw methods to
count the transactions

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Inheritance Hierarchies

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Self Check 10.1
What is the purpose of the JTextComponent class in Figure 2?
Answer: To express the common behavior of text variables
and text components.

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Self Check 10.2
Why don’t we place the addInterest method in the
BankAccount class?
Answer: Not all bank accounts earn interest.

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Inheritance Hierarchies
• Inheritance is a mechanism for extending existing classes by
adding instance variables and methods:
class SavingsAccount extends BankAccount
{
added instance variables
new methods
}

• A subclass inherits the methods of its superclass:
SavingsAccount collegeFund = new SavingsAccount(10);
// Savings account with 10% interest
collegeFund.deposit(500);
// OK to use BankAccount method with SavingsAccount object

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Inheritance Hierarchies
• In subclass, specify added instance variables, added methods,
and changed or overridden methods:
public class SavingsAccount extends BankAccount
{
private double interestRate;
public SavingsAccount(double rate)
{
Constructor implementation
}
public void addInterest()
{
Method implementation
}
}
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Inheritance Hierarchies
• Instance variables declared in the superclass are present in
subclass objects
• SavingsAccount object inherits the balance instance variable
from BankAccount, and gains one additional instance variable,
interestRate:

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Inheritance Hierarchies
• Implement the new addInterest method:
public class SavingsAccount extends BankAccount
{
private double interestRate;
public SavingsAccount(double rate)
{
interestRate = rate;
}
public void addInterest()
{
double interest = getBalance() * interestRate / 100;
deposit(interest);
}
}

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Inheritance Hierarchies
• A subclass has no access to private instance variables of its
superclass
• Encapsulation: addInterest calls getBalance rather than
updating the balance variable of the superclass (variable is
private)
• Note that addInterest calls getBalance without specifying
an implicit parameter (the calls apply to the same object)
• Inheriting from a class differs from implementing an interface:
the subclass inherits behavior from the superclass

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch10/accounts/SavingsAccount.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

/**
An account that earns interest at a fixed rate.
*/
public class SavingsAccount extends BankAccount
{
private double interestRate;
/**
Constructs a bank account with a given interest rate.
@param rate the interest rate
*/
public SavingsAccount(double rate)
{
interestRate = rate;
}

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch10/accounts/SavingsAccount.java (cont.)
17
18
19
20
21
22
23
24
25

/**
Adds the earned interest to the account balance.
*/
public void addInterest()
{
double interest = getBalance() * interestRate / 100;
deposit(interest);
}
}

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Syntax 10.1 Inheritance

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Self Check 10.3
Which instance variables does an object of class
SavingsAccount have?
Answer: Two instance variables: balance and
interestRate.

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Self Check 10.4
Name four methods that you can apply to SavingsAccount
objects.
Answer: deposit, withdraw, getBalance, and
addInterest.

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Self Check 10.5
If the class Manager extends the class Employee, which class is
the superclass and which is the subclass?
Answer: Manager is the subclass; Employee is the
superclass.

Big Java by Cay Big Java by Cay Horstmann
Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Common Error: Shadowing Instance Variables
• A subclass has no access to the private instance variables of the
superclass:
public class SavingsAccount extends BankAccount
{
public void addInterest()
{
double interest = getBalance() * interestRate / 100;
balance = balance + interest; // Error
}
. . .
}

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Common Error: Shadowing Instance Variables
• Beginner’s error: “solve” this problem by adding another
instance variable with same name:
public class SavingsAccount extends BankAccount
{
private double balance; // Don’t
public void addInterest()
{
double interest = getBalance() * interestRate / 100;
balance = balance + interest; // Compiles but doesn’t
// update the correct balance
}
. . .
}

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Common Error: Shadowing Instance Variables
• Now the addInterest method compiles, but it doesn’t update the
correct balance!

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Overriding Methods
• A subclass method overrides a superclass method if it has the
same name and parameter types as a superclass method
• When such a method is applied to a subclass object, the overriding
method is executed

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Overriding Methods
• Example: deposit and withdraw methods of the
CheckingAccount class override the deposit and withdraw
methods of the BankAccount class to handle transaction fees:
public class BankAccount
{
. . .
public void deposit(double amount) { . . . }
public void withdraw(double amount) { . . . }
public double getBalance() { . . . }
}
public class CheckingAccount extends BankAccount
{
. . .
public void deposit(double amount) { . . . }
public void withdraw(double amount) { . . . }
public void deductFees() { . . . }
}
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Overriding Methods
• Problem: Overriding method deposit can't simply add amount
to balance:
public class CheckingAccount extends BankAccount
{
. . .
public void deposit(double amount)
{
transactionCount++;
// Now add amount to balance
balance = balance + amount; // Error
}
}

• If you want to modify a private superclass instance variable, you
must use a public method of the superclass
• deposit method of CheckingAccount must invoke the
deposit method of BankAccount
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Overriding Methods
• Idea:
public class CheckingAccount extends BankAccount
{
public void deposit(double amount)
{
transactionCount++;
// Now add amount to balance
deposit; // Not complete
}
}

• Won't work because compiler interprets
deposit(amount);

as
this.deposit(amount);

which calls the method we are currently writing ⇒ infinite
recursion
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Overriding Methods
• Use the super reserved word to call a method of the
superclass:
public class CheckingAccount extends BankAccount
{
public void deposit(double amount)
{
transactionCount++;
// Now add amount to balance
super.deposit
}
}

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Overriding Methods
• Remaining methods of CheckingAccount also invoke a
superclass method:
public class CheckingAccount extends BankAccount
{
private static final int FREE_TRANSACTIONS = 3;
private static final double TRANSACTION_FEE = 2.0;
private int transactionCount;
. . .
public void withdraw(double amount
{
transactionCount++;
// Now subtract amount from balance
super.withdraw(amount);
}
Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Overriding Methods (cont.)
public void deductFees()
{
if (transactionCount > FREE_TRANSACTIONS)
{
double fees = TRANSACTION_FEE *
(transactionCount - FREE_TRANSACTIONS);
super.withdraw(fees);
}
transactionCount = 0;
}
. . .
}

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Syntax 10.2 Calling a Superclass Method

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Animation 10.1: Inheritance

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Self Check 10.6
Categorize the methods of the SavingsAccount class as
inherited, new, and overridden.
Answer: The SavingsAccount class inherits the deposit,
withdraw, and getBalance methods. The addInterest
method is new. No methods override superclass methods.

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Self Check 10.7
Why does the withdraw method of the CheckingAccount
class call super.withdraw?
Answer: It needs to reduce the balance, and it cannot access
the balance variable directly.

Big Java by Cay Big Java by Cay Horstmann
Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Self Check 10.8
Why does the deductFees method set the transaction count to
zero?
Answer: So that the count can reflect the number of
transactions for the following month.

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Subclass Construction
• To call the superclass constructor, use the super reserved word
in the first statement of the subclass constructor:
public class CheckingAccount extends BankAccount
{
public CheckingAccount(double initialBalance)
{
// Construct superclass
super(initialBalance);
// Initialize transaction count
transactionCount = 0;
}
...
}

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Subclass Construction
• When subclass constructor doesn't call superclass constructor,
the superclass must have a constructor with no parameters
• If, however, all constructors of the superclass require parameters, then
the compiler reports an error

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch10/accounts/CheckingAccount.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

/**
A checking account that charges transaction fees.
*/
public class CheckingAccount extends BankAccount
{
private static final int FREE_TRANSACTIONS = 3;
private static final double TRANSACTION_FEE = 2.0;
private int transactionCount;
/**
Constructs a checking account with a given balance.
@param initialBalance the initial balance
*/
public CheckingAccount(double initialBalance)
{
// Construct superclass
super(initialBalance);
// Initialize transaction count
transactionCount = 0;
}

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch10/accounts/CheckingAccount.java (cont.)
24
25
26
27
28
29
30
31
32
33
34
35
36
37

public void deposit(double amount)
{
transactionCount++;
// Now add amount to balance
super.deposit(amount);
}
public void withdraw(double amount)
{
transactionCount++;
// Now subtract amount from balance
super.withdraw(amount);
}

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch10/accounts/CheckingAccount.java (cont.)
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

/**
Deducts the accumulated fees and resets the
transaction count.
*/
public void deductFees()
{
if (transactionCount > FREE_TRANSACTIONS)
{
double fees = TRANSACTION_FEE *
(transactionCount - FREE_TRANSACTIONS);
super.withdraw(fees);
}
transactionCount = 0;
}
}

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Syntax 10.3 Calling a Superclass Constructor

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Self Check 10.9
Why didn’t the SavingsAccount constructor in Section 10.2 call
its superclass constructor?
Answer: It was content to use the default constructor of the
superclass, which sets the balance to zero.

Big Java by Cay Big Java by Cay Horstmann
Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Self Check 10.10
When you invoke a superclass method with the super keyword,
does the call have to be the first statement of the subclass
method?
Answer: No — this is a requirement only for constructors. For
example, the SavingsAccount.deposit method first
increments the transaction count, then calls the superclass
method.

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Converting Between Subclass and Superclass Types
• OK to convert 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

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Converting Between Subclass and Superclass Types
• Superclass references don’t know the full story:
anAccount.deposit(1000); // OK
anAccount.addInterest();
// No--not a method of the class to which anAccount
// belongs

• Why would anyone want to know less about an object?
• Reuse code that knows about the superclass but not the subclass:
public void transfer(double amount, BankAccount other)
{
withdraw(amount);
other.deposit(amount);
}

Can be used to transfer money from any type of BankAccount
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Converting Between Subclass and Superclass Types
• Occasionally you need to convert from a superclass reference
to a subclass reference:
BankAccount anAccount = (BankAccount) anObject;

• This cast is dangerous: If you are wrong, an exception is thrown
• Solution: Use the instanceof operator
• instanceof: Tests whether an object belongs to a particular
type:
if (anObject instanceof BankAccount)
{
BankAccount anAccount = (BankAccount) anObject;
...
}
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Syntax 10.4 The instanceof Operator

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Self Check 10.11
Why did the second parameter of the transfer method have to
be of type BankAccount and not, for example,
SavingsAccount?
Answer: We want to use the method for all kinds of bank
accounts. Had we used a parameter of type
SavingsAccount, we couldn’t have called the method with a
CheckingAccount object.

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Self Check 10.12
Why can’t we change the second parameter of the transfer
method to the type Object?
Answer: We cannot invoke the deposit method on a
variable of type Object.

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Polymorphism and Inheritance
• Type of a variable doesn’t completely determine type of object to
which it refers:
BankAccount aBankAccount = new SavingsAccount(1000);
// aBankAccount holds a reference to a SavingsAccount
• BankAccount anAccount = new CheckingAccount();
anAccount.deposit(1000);
Which deposit method is called?

• Dynamic method lookup: When the virtual machine calls an
instance method, it locates the method of the implicit
parameter's class

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Polymorphism and Inheritance
• Example:
public void transfer(double amount, BankAccount other)
{
withdraw(amount);
other.deposit(amount);
}

• When you call
anAccount.transfer(1000, anotherAccount);

two method calls result:
anAccount.withdraw(1000);
anotherAccount.deposit(1000);

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Polymorphism and Inheritance
• Polymorphism: Ability to treat objects with differences in
behavior in a uniform way
• The first method call
withdraw(amount);

is a shortcut for
this.withdraw(amount);

• this can refer to a BankAccount or a subclass object

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch10/accounts/AccountTester.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

/**
This program tests the BankAccount class and
its subclasses.
*/
public class AccountTester
{
public static void main(String[] args)
{
SavingsAccount momsSavings = new SavingsAccount(0.5);
CheckingAccount harrysChecking = new CheckingAccount(100);
momsSavings.deposit(10000);
momsSavings.transfer(2000, harrysChecking);
harrysChecking.withdraw(1500);
harrysChecking.withdraw(80);
momsSavings.transfer(1000, harrysChecking);
harrysChecking.withdraw(400);

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch10/accounts/AccountTester.java (cont.)
22
23
24
25
26
27
28
29
30
31
32
33
34

// Simulate end of month
momsSavings.addInterest();
harrysChecking.deductFees();
System.out.println("Mom’s savings balance: "
+ momsSavings.getBalance());
System.out.println("Expected: 7035");
System.out.println("Harry’s checking balance: "
+ harrysChecking.getBalance());
System.out.println("Expected: 1116");
}
}

Program Run:
Mom's savings balance: 7035.0
Expected: 7035
Harry's checking balance: 1116.0
Expected: 1116
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Self Check 10.13
If a is a variable of type BankAccount that holds a non-null
reference, what do you know about the object to which a refers?
Answer: The object is an instance of BankAccount or one of
its subclasses.

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Self Check 10.14
If a refers to a checking account, what is the effect of calling
a.transfer(1000, a)?
Answer: The balance of a is unchanged, and the transaction
count is incremented twice.

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Protected Access
• Protected features can be accessed by all subclasses and by all
classes in the same package
• Solves the problem that CheckingAccount methods need
access to the balance instance variable of the superclass
BankAccount:
public class BankAccount
{
. . .
protected double balance;
}

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Protected Access
• The designer of the superclass has no control over the authors
of subclasses:
• Any of the subclass methods can corrupt the superclass data
• Classes with protected instance variables are hard to modify — the
protected variables cannot be changed, because someone somewhere
out there might have written a subclass whose code depends on them

• Protected data can be accessed by all methods of classes in the
same package
• It is best to leave all data private and provide accessor methods
for the data

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Object: The Cosmic Superclass
• All classes defined without an explicit extends clause
automatically extend Object:

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Object: The Cosmic Superclass
• Most useful methods:
• String toString()
• boolean equals(Object otherObject)
• Object clone()

• Good idea to override these methods in your classes

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
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]"

• 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]"

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Overriding the toString Method
• Object.toString prints 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"

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Overriding the toString Method
• To provide a nicer representation of an object, override
toString:
public String toString()
{
return "BankAccount[balance=" + balance + "]";
}

• This works better:
BankAccount momsSavings = new BankAccount(5000);
String s = momsSavings.toString();
// Sets s to "BankAccount[balance=5000]"

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Overriding the equals Method
• equals tests for same contents:
if (coin1.equals(coin2)) . . .
// Contents are the same

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Overriding the equals Method
• == tests for references to the same object:
if (coin1 == (coin2)) . . .
// Objects are the same

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Overriding the equals Method
• Need to override the equals method of the Object class:
public class Coin
{
...
public boolean equals(Object otherObject)
{
...
}
...
}

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Overriding the equals Method
• Cannot change parameter type; use a cast instead:
public class Coin
{
...
public boolean equals(Object otherObject)
{
Coin other = (Coin) otherObject;
return name.equals(other.name) && value ==
other.value;
}
...
}

• You should also override the hashCode method so that equal
objects have the same hash code
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
The clone Method
• Copying an object reference gives two references to same
object:
BankAccount account = newBankAccount(1000);
BankAccount account2 = account;
account2.deposit(500); // Now both account and account2
// refer to a bank account with a balance of 1500

• Sometimes, need to make a copy of the object:

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
The clone Method
• Implement clone method to make a new object with the same
state as an existing object
• Use clone:
BankAccount clonedAccount =
(BankAccount) account.clone();

• Must cast return value because return type is Object

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
The Object.clone Method
• Creates shallow copies:

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
The Object.clone Method
• Does not systematically clone all subobjects
• Must be used with caution
• It is declared as protected; prevents from accidentally calling
x.clone() if the class to which x belongs hasn’t redefined
clone to be public
• You should override the clone method with care (see Special
Topic 10.6)

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Self Check 10.15
Should the call x.equals(x) always return true?
Answer: It certainly should — unless, of course, x is null.

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Self Check 10.16
Can you implement equals in terms of toString? Should you?
Answer: If toString returns a string that describes all
instance variables, you can simply call toString on the
implicit and explicit parameters, and compare the results.
However, comparing the variables is more efficient than
converting them into strings.

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Scripting Languages

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Using Inheritance to Customize Frames
• Use inheritance for complex frames to make programs easier to
understand
• Design a subclass of JFrame
• Store the components as instance variables
• Initialize them in the constructor of your subclass
• If initialization code gets complex, simply add some helper
methods

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch10/frame/InvestmentFrame.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

import
import
import
import
import
import
import

java.awt.event.ActionEvent;
java.awt.event.ActionListener;
javax.swing.JButton;
javax.swing.JFrame;
javax.swing.JLabel;
javax.swing.JPanel;
javax.swing.JTextField;

public class InvestmentFrame extends JFrame
{
private JButton button;
private JLabel label;
private JPanel panel;
private BankAccount account;
private static final int FRAME_WIDTH = 400;
private static final int FRAME_HEIGHT = 100;
private static final double INTEREST_RATE = 10;
private static final double INITIAL_BALANCE = 1000;

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
ch10/frame/InvestmentFrame.java
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

public InvestmentFrame()
{
account = new BankAccount(INITIAL_BALANCE);
// Use instance variables for components
label = new JLabel("balance: " + account.getBalance());
// Use helper methods
createButton();
createPanel();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
private void createButton()
{
button = new JButton("Add Interest");
ActionListener listener = new AddInterestListener();
button.addActionListener(listener);
}

Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Example: Investment Viewer Program (cont.)
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60

private void createPanel()
{
panel = new JPanel();
panel.add(button);
panel.add(label);
add(panel);
}
class AddInterestListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
double interest = account.getBalance() * INTEREST_RATE / 100;
account.deposit(interest);
label.setText("balance: " + account.getBalance());
}
}
}

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Example: Investment Viewer Program
Of course, we still need a class with a main method:
1
2
3
4
5
6
7
8
9
10
11
12
13
14

import javax.swing.JFrame;
/**
This program displays the growth of an investment.
*/
public class InvestmentViewer2
{
public static void main(String[] args)
{
JFrame frame = new InvestmentFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Self Check 10.17
How many Java source files are required by the investment
viewer application when we use inheritance to define the frame
class?
Answer: Three: InvestmentFrameViewer,
InvestmentFrame, and BankAccount.

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Self Check 10.18
Why does the InvestmentFrame constructor call
setSize(FRAME_WIDTH, FRAME_HEIGHT), whereas the main
method of the investment viewer class in Chapter 9 called
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT)?
Answer: The InvestmentFrame constructor adds the panel
to itself.

Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.

More Related Content

Viewers also liked

Viewers also liked (20)

Ch08
Ch08Ch08
Ch08
 
83341 ch14 jacobsen
83341 ch14 jacobsen83341 ch14 jacobsen
83341 ch14 jacobsen
 
Chapter 1: Understanding Policy
Chapter 1: Understanding Policy Chapter 1: Understanding Policy
Chapter 1: Understanding Policy
 
Chapter 11
Chapter 11Chapter 11
Chapter 11
 
Chapter 2: Policy Elements and style
Chapter 2: Policy Elements and style Chapter 2: Policy Elements and style
Chapter 2: Policy Elements and style
 
Chap10
Chap10Chap10
Chap10
 
Chap14
Chap14Chap14
Chap14
 
Chap03
Chap03Chap03
Chap03
 
83341 ch32 jacobsen
83341 ch32 jacobsen83341 ch32 jacobsen
83341 ch32 jacobsen
 
Chap05
Chap05Chap05
Chap05
 
Chap02
Chap02Chap02
Chap02
 
Chap04
Chap04Chap04
Chap04
 
Chapter 3 cells
Chapter 3  cellsChapter 3  cells
Chapter 3 cells
 
Lecture 1 interfaces and polymorphism
Lecture 1    interfaces and polymorphismLecture 1    interfaces and polymorphism
Lecture 1 interfaces and polymorphism
 
Ch15
Ch15Ch15
Ch15
 
Chap09
Chap09Chap09
Chap09
 
Chapter 7 joints
Chapter 7  jointsChapter 7  joints
Chapter 7 joints
 
83341 ch07 jacobsen
83341 ch07 jacobsen83341 ch07 jacobsen
83341 ch07 jacobsen
 
Lecture 4 recursion
Lecture 4    recursionLecture 4    recursion
Lecture 4 recursion
 
Chapter 12: Provider Cost Finding Methods
Chapter 12: Provider Cost Finding MethodsChapter 12: Provider Cost Finding Methods
Chapter 12: Provider Cost Finding Methods
 

Similar to Inheritance and Polymorphism in Java

2CPP07 - Inheritance
2CPP07 - Inheritance2CPP07 - Inheritance
2CPP07 - InheritanceMichael Heron
 
Lecture 3 object-oriented design
Lecture 3    object-oriented designLecture 3    object-oriented design
Lecture 3 object-oriented designNada G.Youssef
 
Inheritance
InheritanceInheritance
InheritanceFraboni Ec
 
Inheritance
InheritanceInheritance
InheritanceJames Wong
 
Inheritance
InheritanceInheritance
InheritanceTony Nguyen
 
inheritance and polymorphism
inheritance and polymorphisminheritance and polymorphism
inheritance and polymorphismKarthigaGunasekaran1
 
Java htp6e 09
Java htp6e 09Java htp6e 09
Java htp6e 09Ayesha ch
 
Salesforce lwc development workshops session #6
Salesforce lwc development workshops  session #6Salesforce lwc development workshops  session #6
Salesforce lwc development workshops session #6Rahul Gawale
 
2. oop with c++ get 410 day 2
2. oop with c++ get 410   day 22. oop with c++ get 410   day 2
2. oop with c++ get 410 day 2Mukul kumar Neal
 
Inheritance
InheritanceInheritance
Inheritancezindadili
 
C++Presentation 2.PPT
C++Presentation 2.PPTC++Presentation 2.PPT
C++Presentation 2.PPTVENARATEKANHURU
 
INHERITANCE.pptx
INHERITANCE.pptxINHERITANCE.pptx
INHERITANCE.pptxAteeqaKokab1
 

Similar to Inheritance and Polymorphism in Java (20)

ch10.ppt
ch10.pptch10.ppt
ch10.ppt
 
Icom4015 lecture7-f16
Icom4015 lecture7-f16Icom4015 lecture7-f16
Icom4015 lecture7-f16
 
CiIC4010-chapter-2-f17
CiIC4010-chapter-2-f17CiIC4010-chapter-2-f17
CiIC4010-chapter-2-f17
 
2CPP07 - Inheritance
2CPP07 - Inheritance2CPP07 - Inheritance
2CPP07 - Inheritance
 
Lecture 3 object-oriented design
Lecture 3    object-oriented designLecture 3    object-oriented design
Lecture 3 object-oriented design
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
inheritance and polymorphism
inheritance and polymorphisminheritance and polymorphism
inheritance and polymorphism
 
Java htp6e 09
Java htp6e 09Java htp6e 09
Java htp6e 09
 
Icom4015 lecture8-f16
Icom4015 lecture8-f16Icom4015 lecture8-f16
Icom4015 lecture8-f16
 
Salesforce lwc development workshops session #6
Salesforce lwc development workshops  session #6Salesforce lwc development workshops  session #6
Salesforce lwc development workshops session #6
 
2. oop with c++ get 410 day 2
2. oop with c++ get 410   day 22. oop with c++ get 410   day 2
2. oop with c++ get 410 day 2
 
Inheritance
InheritanceInheritance
Inheritance
 
C++Presentation 2.PPT
C++Presentation 2.PPTC++Presentation 2.PPT
C++Presentation 2.PPT
 
INHERITANCE.pptx
INHERITANCE.pptxINHERITANCE.pptx
INHERITANCE.pptx
 

More from Nada G.Youssef

مجلة 1
مجلة 1مجلة 1
مجلة 1Nada G.Youssef
 
Chapter 15: PCI Compliance for Merchants
Chapter 15: PCI Compliance for Merchants Chapter 15: PCI Compliance for Merchants
Chapter 15: PCI Compliance for Merchants Nada G.Youssef
 
Chapter 14: Regulatory Compliance for the Healthcare Sector
Chapter 14: Regulatory Compliance for the Healthcare SectorChapter 14: Regulatory Compliance for the Healthcare Sector
Chapter 14: Regulatory Compliance for the Healthcare SectorNada G.Youssef
 
Chapter 13: Regulatory Compliance for Financial Institutions
Chapter 13: Regulatory Compliance for Financial InstitutionsChapter 13: Regulatory Compliance for Financial Institutions
Chapter 13: Regulatory Compliance for Financial InstitutionsNada G.Youssef
 
Chapter 12: Business Continuity Management
Chapter 12: Business Continuity ManagementChapter 12: Business Continuity Management
Chapter 12: Business Continuity ManagementNada G.Youssef
 
Chapter 11: Information Security Incident Management
Chapter 11: Information Security Incident ManagementChapter 11: Information Security Incident Management
Chapter 11: Information Security Incident ManagementNada G.Youssef
 
Chapter 10: Information Systems Acquisition, Development, and Maintenance
			Chapter 10:  Information  Systems Acquisition, Development, and Maintenance			Chapter 10:  Information  Systems Acquisition, Development, and Maintenance
Chapter 10: Information Systems Acquisition, Development, and MaintenanceNada G.Youssef
 
Chapter 9: Access Control Management
Chapter 9: Access Control ManagementChapter 9: Access Control Management
Chapter 9: Access Control ManagementNada G.Youssef
 

More from Nada G.Youssef (20)

مجلة 1
مجلة 1مجلة 1
مجلة 1
 
Chapter Tewlve
Chapter TewlveChapter Tewlve
Chapter Tewlve
 
Chapter Eleven
Chapter ElevenChapter Eleven
Chapter Eleven
 
Chapter Ten
Chapter TenChapter Ten
Chapter Ten
 
Chapter Nine
Chapter NineChapter Nine
Chapter Nine
 
Chapter Eight
Chapter Eight Chapter Eight
Chapter Eight
 
Chapter Seven
Chapter SevenChapter Seven
Chapter Seven
 
Chapter Six
Chapter SixChapter Six
Chapter Six
 
Chapter Five
Chapter FiveChapter Five
Chapter Five
 
Chapter Four
Chapter FourChapter Four
Chapter Four
 
Chapter Three
Chapter ThreeChapter Three
Chapter Three
 
Chapter Two
Chapter TwoChapter Two
Chapter Two
 
Chapter one
Chapter oneChapter one
Chapter one
 
Chapter 15: PCI Compliance for Merchants
Chapter 15: PCI Compliance for Merchants Chapter 15: PCI Compliance for Merchants
Chapter 15: PCI Compliance for Merchants
 
Chapter 14: Regulatory Compliance for the Healthcare Sector
Chapter 14: Regulatory Compliance for the Healthcare SectorChapter 14: Regulatory Compliance for the Healthcare Sector
Chapter 14: Regulatory Compliance for the Healthcare Sector
 
Chapter 13: Regulatory Compliance for Financial Institutions
Chapter 13: Regulatory Compliance for Financial InstitutionsChapter 13: Regulatory Compliance for Financial Institutions
Chapter 13: Regulatory Compliance for Financial Institutions
 
Chapter 12: Business Continuity Management
Chapter 12: Business Continuity ManagementChapter 12: Business Continuity Management
Chapter 12: Business Continuity Management
 
Chapter 11: Information Security Incident Management
Chapter 11: Information Security Incident ManagementChapter 11: Information Security Incident Management
Chapter 11: Information Security Incident Management
 
Chapter 10: Information Systems Acquisition, Development, and Maintenance
			Chapter 10:  Information  Systems Acquisition, Development, and Maintenance			Chapter 10:  Information  Systems Acquisition, Development, and Maintenance
Chapter 10: Information Systems Acquisition, Development, and Maintenance
 
Chapter 9: Access Control Management
Chapter 9: Access Control ManagementChapter 9: Access Control Management
Chapter 9: Access Control Management
 

Recently uploaded

4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxnelietumpap1
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 

Recently uploaded (20)

Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptx
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 

Inheritance and Polymorphism in Java

  • 1. Chapter 10 – Inheritance Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 2. Chapter Goals • To learn about inheritance • To understand how to inherit and override superclass methods • To be able to invoke superclass constructors • To learn about protected and package access control • To understand the common superclass Object and to override its toString and equals methods G To use inheritance for customizing user interfaces Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 3. Inheritance Hierarchies • Often categorize concepts into hierarchies: Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 4. Inheritance Hierarchies • Set of classes can form an inheritance hierarchy • Classes representing the most general concepts are near the root, more specialized classes towards the branches: Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 5. Inheritance Hierarchies • Superclass: more general class • Subclass: more specialized class that inherits from the superclass • Example: JPanel is a subclass of JComponent Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 6. Inheritance Hierarchies • Example: Different account types: 1. Checking account: •No interest •Small number of free transactions per month •Charges transaction fee for additional transactions 2. Savings account: •Earns interest that compounds monthly • Superclass: BankAccount • Subclasses: CheckingAccount & SavingsAccount Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 7. Inheritance Hierarchies • Behavior of account classes: • All support getBalance method • Also support deposit and withdraw methods, but implementation details differ • Checking account needs a method deductFees to deduct the monthly fees and to reset the transaction counter • Checking account must override deposit and withdraw methods to count the transactions Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 8. Inheritance Hierarchies Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 9. Self Check 10.1 What is the purpose of the JTextComponent class in Figure 2? Answer: To express the common behavior of text variables and text components. Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 10. Self Check 10.2 Why don’t we place the addInterest method in the BankAccount class? Answer: Not all bank accounts earn interest. Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 11. Inheritance Hierarchies • Inheritance is a mechanism for extending existing classes by adding instance variables and methods: class SavingsAccount extends BankAccount { added instance variables new methods } • A subclass inherits the methods of its superclass: SavingsAccount collegeFund = new SavingsAccount(10); // Savings account with 10% interest collegeFund.deposit(500); // OK to use BankAccount method with SavingsAccount object Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 12. Inheritance Hierarchies • In subclass, specify added instance variables, added methods, and changed or overridden methods: public class SavingsAccount extends BankAccount { private double interestRate; public SavingsAccount(double rate) { Constructor implementation } public void addInterest() { Method implementation } } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 13. Inheritance Hierarchies • Instance variables declared in the superclass are present in subclass objects • SavingsAccount object inherits the balance instance variable from BankAccount, and gains one additional instance variable, interestRate: Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 14. Inheritance Hierarchies • Implement the new addInterest method: public class SavingsAccount extends BankAccount { private double interestRate; public SavingsAccount(double rate) { interestRate = rate; } public void addInterest() { double interest = getBalance() * interestRate / 100; deposit(interest); } } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 15. Inheritance Hierarchies • A subclass has no access to private instance variables of its superclass • Encapsulation: addInterest calls getBalance rather than updating the balance variable of the superclass (variable is private) • Note that addInterest calls getBalance without specifying an implicit parameter (the calls apply to the same object) • Inheriting from a class differs from implementing an interface: the subclass inherits behavior from the superclass Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 16. ch10/accounts/SavingsAccount.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 /** An account that earns interest at a fixed rate. */ public class SavingsAccount extends BankAccount { private double interestRate; /** Constructs a bank account with a given interest rate. @param rate the interest rate */ public SavingsAccount(double rate) { interestRate = rate; } Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 17. ch10/accounts/SavingsAccount.java (cont.) 17 18 19 20 21 22 23 24 25 /** Adds the earned interest to the account balance. */ public void addInterest() { double interest = getBalance() * interestRate / 100; deposit(interest); } } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 18. Syntax 10.1 Inheritance Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 19. Self Check 10.3 Which instance variables does an object of class SavingsAccount have? Answer: Two instance variables: balance and interestRate. Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 20. Self Check 10.4 Name four methods that you can apply to SavingsAccount objects. Answer: deposit, withdraw, getBalance, and addInterest. Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 21. Self Check 10.5 If the class Manager extends the class Employee, which class is the superclass and which is the subclass? Answer: Manager is the subclass; Employee is the superclass. Big Java by Cay Big Java by Cay Horstmann Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 22. Common Error: Shadowing Instance Variables • A subclass has no access to the private instance variables of the superclass: public class SavingsAccount extends BankAccount { public void addInterest() { double interest = getBalance() * interestRate / 100; balance = balance + interest; // Error } . . . } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 23. Common Error: Shadowing Instance Variables • Beginner’s error: “solve” this problem by adding another instance variable with same name: public class SavingsAccount extends BankAccount { private double balance; // Don’t public void addInterest() { double interest = getBalance() * interestRate / 100; balance = balance + interest; // Compiles but doesn’t // update the correct balance } . . . } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 24. Common Error: Shadowing Instance Variables • Now the addInterest method compiles, but it doesn’t update the correct balance! Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 25. Overriding Methods • A subclass method overrides a superclass method if it has the same name and parameter types as a superclass method • When such a method is applied to a subclass object, the overriding method is executed Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 26. Overriding Methods • Example: deposit and withdraw methods of the CheckingAccount class override the deposit and withdraw methods of the BankAccount class to handle transaction fees: public class BankAccount { . . . public void deposit(double amount) { . . . } public void withdraw(double amount) { . . . } public double getBalance() { . . . } } public class CheckingAccount extends BankAccount { . . . public void deposit(double amount) { . . . } public void withdraw(double amount) { . . . } public void deductFees() { . . . } } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 27. Overriding Methods • Problem: Overriding method deposit can't simply add amount to balance: public class CheckingAccount extends BankAccount { . . . public void deposit(double amount) { transactionCount++; // Now add amount to balance balance = balance + amount; // Error } } • If you want to modify a private superclass instance variable, you must use a public method of the superclass • deposit method of CheckingAccount must invoke the deposit method of BankAccount Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 28. Overriding Methods • Idea: public class CheckingAccount extends BankAccount { public void deposit(double amount) { transactionCount++; // Now add amount to balance deposit; // Not complete } } • Won't work because compiler interprets deposit(amount); as this.deposit(amount); which calls the method we are currently writing ⇒ infinite recursion Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 29. Overriding Methods • Use the super reserved word to call a method of the superclass: public class CheckingAccount extends BankAccount { public void deposit(double amount) { transactionCount++; // Now add amount to balance super.deposit } } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 30. Overriding Methods • Remaining methods of CheckingAccount also invoke a superclass method: public class CheckingAccount extends BankAccount { private static final int FREE_TRANSACTIONS = 3; private static final double TRANSACTION_FEE = 2.0; private int transactionCount; . . . public void withdraw(double amount { transactionCount++; // Now subtract amount from balance super.withdraw(amount); } Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 31. Overriding Methods (cont.) public void deductFees() { if (transactionCount > FREE_TRANSACTIONS) { double fees = TRANSACTION_FEE * (transactionCount - FREE_TRANSACTIONS); super.withdraw(fees); } transactionCount = 0; } . . . } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 32. Syntax 10.2 Calling a Superclass Method Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 33. Animation 10.1: Inheritance Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 34. Self Check 10.6 Categorize the methods of the SavingsAccount class as inherited, new, and overridden. Answer: The SavingsAccount class inherits the deposit, withdraw, and getBalance methods. The addInterest method is new. No methods override superclass methods. Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 35. Self Check 10.7 Why does the withdraw method of the CheckingAccount class call super.withdraw? Answer: It needs to reduce the balance, and it cannot access the balance variable directly. Big Java by Cay Big Java by Cay Horstmann Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 36. Self Check 10.8 Why does the deductFees method set the transaction count to zero? Answer: So that the count can reflect the number of transactions for the following month. Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 37. Subclass Construction • To call the superclass constructor, use the super reserved word in the first statement of the subclass constructor: public class CheckingAccount extends BankAccount { public CheckingAccount(double initialBalance) { // Construct superclass super(initialBalance); // Initialize transaction count transactionCount = 0; } ... } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 38. Subclass Construction • When subclass constructor doesn't call superclass constructor, the superclass must have a constructor with no parameters • If, however, all constructors of the superclass require parameters, then the compiler reports an error Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 39. ch10/accounts/CheckingAccount.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 /** A checking account that charges transaction fees. */ public class CheckingAccount extends BankAccount { private static final int FREE_TRANSACTIONS = 3; private static final double TRANSACTION_FEE = 2.0; private int transactionCount; /** Constructs a checking account with a given balance. @param initialBalance the initial balance */ public CheckingAccount(double initialBalance) { // Construct superclass super(initialBalance); // Initialize transaction count transactionCount = 0; } Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 40. ch10/accounts/CheckingAccount.java (cont.) 24 25 26 27 28 29 30 31 32 33 34 35 36 37 public void deposit(double amount) { transactionCount++; // Now add amount to balance super.deposit(amount); } public void withdraw(double amount) { transactionCount++; // Now subtract amount from balance super.withdraw(amount); } Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 41. ch10/accounts/CheckingAccount.java (cont.) 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 /** Deducts the accumulated fees and resets the transaction count. */ public void deductFees() { if (transactionCount > FREE_TRANSACTIONS) { double fees = TRANSACTION_FEE * (transactionCount - FREE_TRANSACTIONS); super.withdraw(fees); } transactionCount = 0; } } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 42. Syntax 10.3 Calling a Superclass Constructor Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 43. Self Check 10.9 Why didn’t the SavingsAccount constructor in Section 10.2 call its superclass constructor? Answer: It was content to use the default constructor of the superclass, which sets the balance to zero. Big Java by Cay Big Java by Cay Horstmann Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 44. Self Check 10.10 When you invoke a superclass method with the super keyword, does the call have to be the first statement of the subclass method? Answer: No — this is a requirement only for constructors. For example, the SavingsAccount.deposit method first increments the transaction count, then calls the superclass method. Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 45. Converting Between Subclass and Superclass Types • OK to convert 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 Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 46. Converting Between Subclass and Superclass Types • Superclass references don’t know the full story: anAccount.deposit(1000); // OK anAccount.addInterest(); // No--not a method of the class to which anAccount // belongs • Why would anyone want to know less about an object? • Reuse code that knows about the superclass but not the subclass: public void transfer(double amount, BankAccount other) { withdraw(amount); other.deposit(amount); } Can be used to transfer money from any type of BankAccount Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 47. Converting Between Subclass and Superclass Types • Occasionally you need to convert from a superclass reference to a subclass reference: BankAccount anAccount = (BankAccount) anObject; • This cast is dangerous: If you are wrong, an exception is thrown • Solution: Use the instanceof operator • instanceof: Tests whether an object belongs to a particular type: if (anObject instanceof BankAccount) { BankAccount anAccount = (BankAccount) anObject; ... } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 48. Syntax 10.4 The instanceof Operator Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 49. Self Check 10.11 Why did the second parameter of the transfer method have to be of type BankAccount and not, for example, SavingsAccount? Answer: We want to use the method for all kinds of bank accounts. Had we used a parameter of type SavingsAccount, we couldn’t have called the method with a CheckingAccount object. Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 50. Self Check 10.12 Why can’t we change the second parameter of the transfer method to the type Object? Answer: We cannot invoke the deposit method on a variable of type Object. Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 51. Polymorphism and Inheritance • Type of a variable doesn’t completely determine type of object to which it refers: BankAccount aBankAccount = new SavingsAccount(1000); // aBankAccount holds a reference to a SavingsAccount • BankAccount anAccount = new CheckingAccount(); anAccount.deposit(1000); Which deposit method is called? • Dynamic method lookup: When the virtual machine calls an instance method, it locates the method of the implicit parameter's class Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 52. Polymorphism and Inheritance • Example: public void transfer(double amount, BankAccount other) { withdraw(amount); other.deposit(amount); } • When you call anAccount.transfer(1000, anotherAccount); two method calls result: anAccount.withdraw(1000); anotherAccount.deposit(1000); Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 53. Polymorphism and Inheritance • Polymorphism: Ability to treat objects with differences in behavior in a uniform way • The first method call withdraw(amount); is a shortcut for this.withdraw(amount); • this can refer to a BankAccount or a subclass object Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 54. ch10/accounts/AccountTester.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 /** This program tests the BankAccount class and its subclasses. */ public class AccountTester { public static void main(String[] args) { SavingsAccount momsSavings = new SavingsAccount(0.5); CheckingAccount harrysChecking = new CheckingAccount(100); momsSavings.deposit(10000); momsSavings.transfer(2000, harrysChecking); harrysChecking.withdraw(1500); harrysChecking.withdraw(80); momsSavings.transfer(1000, harrysChecking); harrysChecking.withdraw(400); Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 55. ch10/accounts/AccountTester.java (cont.) 22 23 24 25 26 27 28 29 30 31 32 33 34 // Simulate end of month momsSavings.addInterest(); harrysChecking.deductFees(); System.out.println("Mom’s savings balance: " + momsSavings.getBalance()); System.out.println("Expected: 7035"); System.out.println("Harry’s checking balance: " + harrysChecking.getBalance()); System.out.println("Expected: 1116"); } } Program Run: Mom's savings balance: 7035.0 Expected: 7035 Harry's checking balance: 1116.0 Expected: 1116 Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 56. Self Check 10.13 If a is a variable of type BankAccount that holds a non-null reference, what do you know about the object to which a refers? Answer: The object is an instance of BankAccount or one of its subclasses. Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 57. Self Check 10.14 If a refers to a checking account, what is the effect of calling a.transfer(1000, a)? Answer: The balance of a is unchanged, and the transaction count is incremented twice. Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 58. Protected Access • Protected features can be accessed by all subclasses and by all classes in the same package • Solves the problem that CheckingAccount methods need access to the balance instance variable of the superclass BankAccount: public class BankAccount { . . . protected double balance; } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 59. Protected Access • The designer of the superclass has no control over the authors of subclasses: • Any of the subclass methods can corrupt the superclass data • Classes with protected instance variables are hard to modify — the protected variables cannot be changed, because someone somewhere out there might have written a subclass whose code depends on them • Protected data can be accessed by all methods of classes in the same package • It is best to leave all data private and provide accessor methods for the data Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 60. Object: The Cosmic Superclass • All classes defined without an explicit extends clause automatically extend Object: Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 61. Object: The Cosmic Superclass • Most useful methods: • String toString() • boolean equals(Object otherObject) • Object clone() • Good idea to override these methods in your classes Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 62. 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]" • 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]" Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 63. Overriding the toString Method • Object.toString prints 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" Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 64. Overriding the toString Method • To provide a nicer representation of an object, override toString: public String toString() { return "BankAccount[balance=" + balance + "]"; } • This works better: BankAccount momsSavings = new BankAccount(5000); String s = momsSavings.toString(); // Sets s to "BankAccount[balance=5000]" Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 65. Overriding the equals Method • equals tests for same contents: if (coin1.equals(coin2)) . . . // Contents are the same Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 66. Overriding the equals Method • == tests for references to the same object: if (coin1 == (coin2)) . . . // Objects are the same Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 67. Overriding the equals Method • Need to override the equals method of the Object class: public class Coin { ... public boolean equals(Object otherObject) { ... } ... } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 68. Overriding the equals Method • Cannot change parameter type; use a cast instead: public class Coin { ... public boolean equals(Object otherObject) { Coin other = (Coin) otherObject; return name.equals(other.name) && value == other.value; } ... } • You should also override the hashCode method so that equal objects have the same hash code Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 69. The clone Method • Copying an object reference gives two references to same object: BankAccount account = newBankAccount(1000); BankAccount account2 = account; account2.deposit(500); // Now both account and account2 // refer to a bank account with a balance of 1500 • Sometimes, need to make a copy of the object: Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 70. The clone Method • Implement clone method to make a new object with the same state as an existing object • Use clone: BankAccount clonedAccount = (BankAccount) account.clone(); • Must cast return value because return type is Object Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 71. The Object.clone Method • Creates shallow copies: Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 72. The Object.clone Method • Does not systematically clone all subobjects • Must be used with caution • It is declared as protected; prevents from accidentally calling x.clone() if the class to which x belongs hasn’t redefined clone to be public • You should override the clone method with care (see Special Topic 10.6) Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 73. Self Check 10.15 Should the call x.equals(x) always return true? Answer: It certainly should — unless, of course, x is null. Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 74. Self Check 10.16 Can you implement equals in terms of toString? Should you? Answer: If toString returns a string that describes all instance variables, you can simply call toString on the implicit and explicit parameters, and compare the results. However, comparing the variables is more efficient than converting them into strings. Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 75. Scripting Languages Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 76. Using Inheritance to Customize Frames • Use inheritance for complex frames to make programs easier to understand • Design a subclass of JFrame • Store the components as instance variables • Initialize them in the constructor of your subclass • If initialization code gets complex, simply add some helper methods Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 77. ch10/frame/InvestmentFrame.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 import import import import import import import java.awt.event.ActionEvent; java.awt.event.ActionListener; javax.swing.JButton; javax.swing.JFrame; javax.swing.JLabel; javax.swing.JPanel; javax.swing.JTextField; public class InvestmentFrame extends JFrame { private JButton button; private JLabel label; private JPanel panel; private BankAccount account; private static final int FRAME_WIDTH = 400; private static final int FRAME_HEIGHT = 100; private static final double INTEREST_RATE = 10; private static final double INITIAL_BALANCE = 1000; Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 78. ch10/frame/InvestmentFrame.java 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 public InvestmentFrame() { account = new BankAccount(INITIAL_BALANCE); // Use instance variables for components label = new JLabel("balance: " + account.getBalance()); // Use helper methods createButton(); createPanel(); setSize(FRAME_WIDTH, FRAME_HEIGHT); } private void createButton() { button = new JButton("Add Interest"); ActionListener listener = new AddInterestListener(); button.addActionListener(listener); } Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 79. Example: Investment Viewer Program (cont.) 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 private void createPanel() { panel = new JPanel(); panel.add(button); panel.add(label); add(panel); } class AddInterestListener implements ActionListener { public void actionPerformed(ActionEvent event) { double interest = account.getBalance() * INTEREST_RATE / 100; account.deposit(interest); label.setText("balance: " + account.getBalance()); } } } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 80. Example: Investment Viewer Program Of course, we still need a class with a main method: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 import javax.swing.JFrame; /** This program displays the growth of an investment. */ public class InvestmentViewer2 { public static void main(String[] args) { JFrame frame = new InvestmentFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 81. Self Check 10.17 How many Java source files are required by the investment viewer application when we use inheritance to define the frame class? Answer: Three: InvestmentFrameViewer, InvestmentFrame, and BankAccount. Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
  • 82. Self Check 10.18 Why does the InvestmentFrame constructor call setSize(FRAME_WIDTH, FRAME_HEIGHT), whereas the main method of the investment viewer class in Chapter 9 called frame.setSize(FRAME_WIDTH, FRAME_HEIGHT)? Answer: The InvestmentFrame constructor adds the panel to itself. Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.