S9 Inheritance
S9 Inheritance
1
Inheritance: Definition
n inheritance: a parent-child relationship
between classes
n the objects of your class will now receive all of the state
(fields) and behavior (methods) of the parent class
n constructors and static methods/fields are not inherited
n by default, a class's parent is Object
7
"Is-a" relationships
n "Is-a" relationships represent sets of abilities;
implemented through interfaces and inheritance
System.out.println(b);
System.out.println(f);
n Output:
Ed $9.0
Jen $9.0 (Fee: $2.0)
12
Final Methods and Final Classes
15
Class diagram: inheritance
n inheritance relationships
n hierarchies drawn top-down with arrows from child to parent
16
Access modifiers
n public: visible to all other classes
public class BankAccount
18
Brainstorming
n What are some other examples of possible
inheritance hierarchies?
n Person -> student, faculty…
n Shape -> circle, triangle, rectangle…
n Other examples???
Inheritance
Abstract Classes
n syntax:
super(args); // call parent’s constructor
super.fieldName // access parent’s field
super.methodName(args); // or method
23
super example
public class BankAccount {
private double myBalance;
public void withdraw(double amount) {
myBalance -= amount;
} }