6 7-Inheritance
6 7-Inheritance
Programming
2
Policies for students
■These contents are only used for students
PERSONALLY.
■Students are NOT allowed to modify or
deliver these contents to anywhere or anyone
for any purpose.
3
Objectives
▪Introducing inheritance through
creating subclasses
▪ Improve code reusability
▪ Allowing overriding to replace the
implementation of an inherited method
Textbook
• Chapter 1: Section 1.4 (pg 54 – 56)
• Chapter 9: Section 29.1 (pg 480 –
490)
}
The “extends”
class SavingAcct extends BankAcct { keyword indicates
inheritance
protected double rate; // interest rate
+ getRate() + getAcctNum()
+ payInterest() + getBalance()
+ print() + withdraw()
+ deposit()
+ print()
sa1.print();
sa1.withdraw(50.0); Inherited method from BankAcct
SavingAcct.java
class SavingAcct extends BankAcct {
. . .
To use the print()
public void print() { method from BankAcct
super.print();
System.out.printf("Interest: %.2f%%\n", getRate());
}
}
class BankAcct {
...
}; Person BankAcct
class Person {
private BankAcct myAcct;
}; Dotted arrow
Attribute: Person HAS-A BankAcct
[503005 Lecture 6-7: Inheritance]
27
6. Preventing Inheritance
(“final”)
■ Sometimes, we want to prevent inheritance by
another class (eg: to prevent a subclass from corrupting the
behaviour of its superclass)
■ Use the final keyword
❑ Eg: final class SavingAcct will prevent a subclass to be
created from SavingAcct
■ Sometimes, we want a class to be inheritable, but
want to prevent some of its methods to be overridden
by its subclass
❑ Use the final keyword on the particular method:
public final void payInterest() { … }
will prevent the subclass of SavingAcct from overriding
payInterest()
[503005 Lecture 6-7: Inheritance]
28
7. Constraint of Inheritance
in Java
■ Single inheritance: Subclass can only have a single
superclass
■ Multiple inheritance: Subclass may have more than
one superclass
■ In Java, only single inheritance is allowed
■ (Side note: Java’s alternative to multiple inheritance can be achieved
through the use of interfaces – to be covered later. A Java class may
implement multiple interfaces.)
+ m()
■ Assume all methods print out message of the + n()
form <class name>.<method name>
■ Eg: method m() in class A prints out “A.m”. B C