Title: Introduction to Inheritance
1Introduction to Inheritance
These slides provide only highlights of this
topic. For fuller understanding, please read the
textbook, resources, and study the programming
assignments. You are responsible for all
material in the assigned readings.
2What is Inheritance
Inheritance means that one class incorporates
attributes and behavior from another class -- it
inherits the attributes and behavior.
Generalize
superclass
A subclass (child class) extends a superclass
(parent class). The subclass inherits all the
attributes and behavior of the super. It can
directly access the public protected attributes
and methods of the superclass.
is a
Specialize
subclass
UML notation for inheritance
3Java Code for Inheritance
To create a subclass, use the keyword "extends"
followed by the parent class name.
4Interpretation of Inheritance (1)
- Superclass defines basic behavior and attributes.
5Interpretation of Inheritance (2)
- Subclass can either...
- add new behavior and attributes (extension)
- redefine existing behavior (specialize)
Subclass addToBalance( amt )
void toString( ) String
6Terminology
- Superclass
- Base Class
- Parent class
- Subclass
- Derived Class
- Child class
7Example classes for shapes
Suppose we want to define some classes for
two-dimensional shapes. To avoid duplicating a
lot of common code in each class, we might create
a superclass named "Shape2D". In Shape2D we put
in the common characteristics of shapes. To
define a Triangle, we would extend Shape2D
using class Triangle extends Shape2D In the
Triangle class we add speicalized behavior. For
example the formula to compute the area of a
triangle is area width height / 2
Shape2D
width
double
height
double
showDimension
( )
void
getWidth
( )
double
getHeight
( )
double
setWidth
(
double width
)
void
setHeigth
(
double heigth
)
void
Triangle
-
style
String
area
( )
double
showStyle
( )
void
8Object the Universal Superclass
- All classes in Java are automatically subclasses
of Object. You don't need to write "... extends
Object". - Object provides some common methods for all
classes
java.lang.Object clone() Object equals()
boolean getClass() Class hashCode()
int toString() String wait() void
9Number parent of numeric classes
- Another prodigious parent class is Number.
Number is the parent class of all the numeric
classes. - Number defines but does not implement some
methods that all numeric classes have, such as
longValue( ) and doubleValue( ).
Object
Number
Integer
Long
Float
Double
BigInteger
BigDecimal
10Properties of Inheritance
- A subclass extends the parent class.
- an object of the subclass contain an object of
the parent class - A subclass object exhibits the public/protected/pa
ckage behavior of the parent. - Private attributes/behavior of the parent can
only be accessed from inside the parent class. - A subclass can override methods of the parent
- A subclass can shadow (redefine) attributes of
the parent.
11Example BankAccount
CheckingAccount CheckingAccount( ) withdraw(
) void toString( ) String
12BankAccount class (1)
/ BankAccount a generic bank account / import
java.util.Formatter public class BankAccount
/ static attribute for assigning acct numbers
/ private static long nextID 1 protected
double balance // acct balance private long
accountID // account ID protected String
accountName // acct name / constructor
/ public BankAccount(String name)
accountName name accountID nextID
// assign next ID balance 0
13BankAccount class (2)
/ deposit add money to the account / public
void deposit(double amount) balance
amount / withdraw deduct money but
balance not less than zero / public void
withdraw(double amount) if ( amount gt balance
) throw new RuntimeException("Withdraw
Error you can withdraw at most
"balance) // OK to withdraw balance -
amount
14BankAccount class (3)
public String toString( ) String format
"BankAccount s 010d balance
.2f" return String.format( format, account
Name, accountID, balance ) / test the
BankAccount methods / public static void
main(String args) // create an account
// deposit and withdraw money
15CheckingAccount class (1)
/ Checking Account with overdraft protection.
You can overdraw by up to a credit limit.
/ import java.util.Formatter public class
CheckingAccount extends BankAccount / this
is the overdraft limit (credit line)
/ protected double overDraftLimit
100000 / constructor for checking account
/ public CheckingAccount(String name) //
call the BankAccount constructor super( name
)
16CheckingAccount class (2)
/ withdraw method for checking account
/ public void withdraw( double amount ) if
( amount gt balance overDraftLimit ) //
cannot withdraw System.out.printf( "Error
you can withdraw at most f Baht\n", balanceo
verDraftLimit ) return else balance
- amount // OK to withdraw public String
toString() ... toString similar to
BankAccount ... // end of CheckingAccount
class
17"is a" relationship
- A CheckingAccount is a BankAccount
- A Number is an Object
- A Double is a Number
- X A Fraction has a Double (numerator and
denominator) - ? A Square is a Rectangle
- should Square be a subclass of Rectangle
18Constructor in Inheritance Hierarchy
- To build a building...
- first you have to build the foundation
- then build the first floor
- then build the second floor
- etc... until you build all the floors
19Constructor in Inheritance Hierarchy
- To construct an object of a derived class...
- first you have to construct the base class
(Object) - then construct the 1st subclass of Object
- etc... until you can build the object you want
- Example create a new Double
- Double d new Double( 10.5 )
d Double
Number
Number
Object
Object
Object
20Calling a Constructor
- A constructor of a subclass must either
- explicitly call a constructor of the superclass
- implicitly (by Java compiler) invoke the
superclass default constructor
super( )
super( )
Double
Number
Number
Object
Object
Object
21Explicit Constructor Hierarchy
- A subclass can call a constructor of the
superclass using the reserved name super(...). - this must be the first statement in the subclass
constructor.
public class Superclass public Superclass(
Type param ) // constructor for objects of
Superclass
public class Subclass extends Superclass
public Subclass( Type param ) super(
param )
22Implicit Constructor Hierarchy
- If a class does not explicitly call a "super"
constructor, then Java will implicitly insert a
call to the default constructor of the
superclass super( )
public class Object public Object( ) /
constructor for Object class /
public class Superclass extends Object public
Superclass( ) / default constructor /
super( )
public class Subclass extends Superclass
public Subclass( Type1 arg1, Type2 arg2 )
this.property1 arg1 this.property2
arg2
super( )
23Implicit Constructor Errors
- Suppose the CheckingAccount class does not
explicitly call "super(name)". What happens?
public class CheckingAccount extends BankAccount
public CheckingAccount(String name)
lt-- implicit call to super( ) here if
(Bank.creditCheck(name) Bank.BADCREDIT) over
draftLimit 0 ...
The Java compiler issues an error message
Implicit super constructor BankAccount( ) is
undefined.
24Supplying a Default Constructor
- For the BankAccount hierarchy, this error is
good!It reminds the programmer that he must call
the parameterized constructor of BankAccount. - For hierarchy such as Number, the parent class
should supply a default constructor to avoid
errors in subclasses.
25Binding of Methods to References
- Java determines which instance method should be
called for a method name at run-time. - This is called dynamic binding or late binding.
- This means that you can't tell which actual
method will be called from only the variable type.
Object obj "What am I?" // obj -gt String if
(Math.random() gt 0.5) obj new
BankAccount("Joe") else obj new
CheckingAccount("Checkers","1111") // which
toString will be used? obj.withdraw( )
26Overriding Methods and access
- Q Can a subclass change the visibility of a
method that it overrides? - A a subclass can increase the visibility of an
overridden method, but it cannot decrease the
visibility.
Method in Superclass Method in Subclass public pub
lic protected public protected package
(default) public protected package private anythin
g
27Overriding Methods (1) return type
class BankAccount / withdraw method for
checking account / protected boolean withdraw(
double amount ) .... class
CheckingAccount extends BankAccount _________
boolean withdraw( double amount ) ....
BankAccount b new BankAccount( "Me"
) BankAccount c new CheckingAccountO( "You"
) b.withdraw( 100 ) c.withdraw( 100 )
28Overriding Methods (2) access
- Q Can a subclass change the visibility (access
privilege) of a method that it overrides? - change access from "public" to "protected"
/ withdraw method for checking account
/ protected void withdraw( double amount )
if ( amount gt balance overDraftLimit )
System.out.printf( "Error you can
withdraw at most f Baht\n", balanceoverDraft
Limit ) return /false/ // cannot withdraw
This method is "public" in the BankAccount class.
29Overriding Methods (3) parameters
- Q Can a subclass change the type of a parameter
that it overrides? - change amount from "double" to "long"
/ withdraw method for checking account
/ protected void withdraw( long amount ) if
( amount gt balance overDraftLimit )
System.out.printf( "Error you can
withdraw at most f Baht\n", balanceoverDraft
Limit ) return /false/ // cannot withdraw
This parameter is "double" in the BankAccount
class.
30Overriding Methods and parameters
- Q Can a subclass change the type of a parameter
that it overrides? - A Yes, but then you aren't overriding the
method!If the parameter type is different then
you are creating a new method ("overloading").
/ test the withdraw method / public void
testWithdraw( ) CheckingAccount ca new
CheckingAccount("...") ca.withdraw( 50000
) // this calls CheckingAccount
withdraw() // with overdraft
protection. ca.withdraw( 25000.0 ) // calls
BankAccount withdraw(), no overdraft
31Overriding Methods (4) access super
- Q Can we access the method of the superclass,
even though it has been overridden? - invoke withdraw of BankAccount using "super".
class CheckingAccount extends BankAccount /
withdraw method for checking account
/ protected void withdraw( double amount )
if ( overDraftLimit 0 ) super.withdraw(a
mount) // parent's method else if ( amount gt
balance overDraftLimit ) System.out.printf("E
rror ...") else balance balance - amount
32Overriding Methods (4) access super
- For a better example, consider a Person
superclass and Student subclass. - (Person) p.compareTo( ) compares people by name
- (Student) s.compareTo( ) compares by student ID
first and then name.
public class Student extends Person private
String studentID public int compareTo(Object
other) Student s (Student) other int
comp studentID.compareTo(s.studentID) if (
comp ! 0 )return comp // if studentID is
same, compare by name return
super.compareTo(other)
33Redefining Attributes
- A subclass can redefine an attribute of the
parent class.
Bank Account Numbers Bank Accounts shall use the
following account ID system CheckingAccount have
ID of the form 111(7-digit) SavingAccount have
ID of the form 122(7-digit)
34Redefining Attributes
- The new BankAccount hierarchy is
New method to get the AccountID
CheckingAccount - overDraftLimit withdraw( )
void toString( ) String
SavingsAccount - interestRate toString( )
String
35SavingsAccount
/ Savings Account with interest. / public
class SavingsAccount extends BankAccount
protected double interestRate 0.01 /
constructor for savings account / public
SavingsAccount(String name) super( name ) //
call BankAccount constructor // fix account ID
by prepending 102xxxxxxx accountID
1220000000L accountID10000000 void
setInterestRate(double rate) interestRate
rate
36CheckingAccount
/ Checking Account with overdraft protection.
/ public class CheckingAccount extends
BankAccount protected double overDraftLimit
100000 protected long accountID // define
our own!! / constructor for checking account
/ public CheckingAccount(String name)
super( name ) // call BankAccount
constructor // fix account ID by prepending
102xxxxxxx accountID 1110000000L
accountID10000000
CheckingAccount redefines the accountID
attribute. What is the effect of this?
37Constructor Scenario
- Create A Checking Account
- 1. application invokes new CheckingAccount( )
- 2. CheckingAccount constructor calls super
constructor - 3. BankAccount constructor sets accountID
000000001 - 4. BankAccount constructor returns
- 5. CheckingAccount constructor sets
- accountID 1110000000L accountID1000000L
- What accountID is used on the right hand side?
Run the code and compare results for
SavingsAccount class (does not redefine
accountID) and CheckingAccount (does redefine
accountID).
38Questions About Redefined Attributes
- If a subclass redefines an attribute of the
superclass... - can the subclass still access the superclass
attribute? - can the subclass change the visibility of the
attribute? - Example in CheckingAccount can we declare
- private long accountID
- can the subclass change the datatype of the
attribute? - Example in CheckingAccount can we declare
- protected String accountID
39Review Questions
40Object References
- Q1 Which of these assignments is legal?
/ 1 / BankAccount b1 new CheckingAccount("Nok"
) / 2 / CheckingAccount c1 new
BankAccount("Noi") / 3 / Object o1 new
BankAccount("Maew") / 4 / BankAccount b2 new
Object( )
41Object References
- Q2 What is the effect of this reassignment?
BankAccount ba CheckingAccount ca new
CheckingAccount("Noi") ca.deposit( 100000 ) //
assign to a BankAccount object ba ca
What happens when "ba ca" is executed? 1. It
converts CheckingAccount object to a BankAccount
object. Any extra attributes of CheckingAccount
are lost! 2. It converts CheckingAccount object
to a BankAccount object. Any extra attributes of
CheckingAccount are hidden until it is cast back
to a CheckingAccount object. 3. Has no effect on
the object. 4. This statement is illegal.
42I Want My Checking Account!
- Q3 Suppose a BankAccount reference refers to a
CheckingAccount object. How can you assign it
to a CheckingAccount?
BankAccount ba new CheckingAccount("Jim") Check
ingAccount ca if ( ba instanceof CheckingAccount
) // this is a checking account. ca ???
// make it look like a checking acct how can
you assign the bank account(ba) to ca ?
1. ca ba 2. ca new CheckingAccount( ba )
3. ca ba.clone( ) 4. ca (CheckingAccount)
ba 5. none of the above.
43Overriding equals( )
- The Object class contains a public equals()
method. - Q1 Does this method of BankAccount override the
Object equals() method?
/ compare two BankAccounts using ID / public
boolean equals( BankAccount other ) if (
other null ) return false return accountID
other.accountID
Object a new Object( ) BankAccount b new
BankAccount( "Joe" ) if ( b.equals( a ) )
System.out.println("Same")
44Overriding equals( )
- The Object class contains a public equals()
method. - Q2 CheckingAccount does not have an equals
method. Which equals will be called here?
/ compare two Checking Accounts
/ CheckingAccount ca1 new CheckingAccount(...)
CheckingAccount ca2 new CheckingAccount(...)
... if ( ca1.equals(ca2) ) / accounts are
same /
1. (BankAccount)equals 2. (Object)equals 3.
neither. Its an error because CheckingAccount
doesn't have equals.
45Homework Binding of Methods
- In a previous slide, I wrote that Java determines
which method it should use (for a given method
name) at run-time. For example
Object obj if ( x 1 0 ) obj new
Integer(x) else obj new Double(x) String s
obj.toString( ) // toString() is determined
at runtime
Homework There are at least 3 situations where
Java "binds" a method name to an actual method at
compile time (more efficient for execution). What
are these situations? Give an example of each.
46Summary of Important Concepts
47Subclass has all behavior of the parent
- A subclass has all the behavior of the
superclass. - Example
- Number has a longValue( ) method.
- Double and Fraction are subclasses of Number .
- Therefore, Double and Fraction also have
longValue()
48Calling a method e.talk( )
- Compile Time Binding
- Compiler "binds" a method call to code using the
declared class of the variable - most efficient
- no polymorphism
- When is this used?
- "final" methods
- "final" class
- private methods
- static methods
- constructors
- Runtime Binding
- Method is invoked using the actual type of the
object. - slower
- enables polymorphism
- When is this used?
- Java all methods except "final", "static", or
"private" - C only for virtual methods
49Java
class Animal void talk() console.write("grrrr
r") class Dog Animal void talk()
console.write("woof") void main() Animal
a new Dog() a.talk( ) lt--- which talk
method is invoked?
50C
class Animal virtual void talk()
console.write("grrrrr") class Dog Animal
override void talk() console.write("woof")
void main() Animal a new Dog() a.talk(
) lt--- which talk method is invoked?