CHAPTER 3 Inheritance
CHAPTER 3 Inheritance
Inheritance
1
What is Inheritance?
In the real world: We inherit traits from our
mother and father. We also inherit traits from
our grandmother, grandfather, and ancestors.
We might have similar eyes, the same smile,
a different height . . . but we are in many
ways "derived" from our parents.
5
Solution: Inheritance
• Inheritance allows you to write new classes
that inherit from existing classes
using
inheritance
superclass
Animal
subclass
String name
subclass String getName()
Dog Cat
int fleas int hairballs
int getFleas() int getHairballs()
void speak() void speak() 7
Animal Superclass
public class Animal {
public Animal(String n) {
name = n;
}
12
Subclass Constructor
• The first thing a subclass constructor must do
is call the superclass constructor
public
protected -
default - -
private - - -
19
20
The final Modifier
• The final class cannot be extended:
final class Math {
...
}
21
Variable Type vs Object Type
• Variables have the types they are given when
they are declared and objects have the type of
their class.
27
Employee class
This is a simple super or base class.
class Employee {
// Data
private String firstName, lastName;
// Constructor
public Employee(String fName, String lName) {
firstName= fName; lastName= lName;
}
// Method
public void printData() {
System.out.println(firstName + " " + lastName);}
}
28
Inheritance
Already written:
Class Employee
firstName printData()
lastName
is-a is-a
Class Engineer
Class Manager
firstName firstName
lastName lastName
hoursWorked
salary
printData() wages
getPay()
printData()
getPay()
You next write: 29
Engineer class
Subclass or (directly) derived class
class Engineer extends Employee {
private double wage;
private double hoursWorked;
public Engineer(String fName, String lName,
double rate, double hours) {
super(fName, lName);
wage = rate;
hoursWorked = hours;
}
is-a
Salary
printData
getPay
Class SalesManager
firstName
lastName
Salary
printData
getPay salesBonus
32
SalesManager Class
(Derived class from derived class)
class SalesManager extends Manager {
private double bonus; // Bonus Possible as commission.
34
Output from main method
Fred Smith
Weekly pay: $96.0
Ann Brown
Monthly salary: $1500.0
Mary Kate
Monthly salary: $1250.0
Bonus: $2000.0
36
Class Relationships
• Association is a general binary relationship
that describes an activity between two classes.
For example,
• A student taking a course is an association
between the Student class and the Course
class, and
• A faculty member teaching a course is an
association between the Faculty class and the
Course class.
37
Class Relationships
40
Common Class Relationships
• Composition
- E.g. A Car has a Wheel
• Inheritance
- E.g. Man is a LivingThing
41
Composition example
42
Object Class
• All Java classes implicitly inherit from
java.lang.Object
B x = new B( );
A y = new A( );
44