Chapter 6
Chapter 6
Programming
L. Rafika Maaroufi
1
Chapter6:
Inheritance
2
Objectives
3
Outline
Inheritance in java
Superclasses and Subclasses
Relationship between Superclasses and
Subclasses
4
Inheritance in java
Inheritance in java :
is a mechanism in which one object acquires all
the properties and behaviors of a parent object
5
A hierarchical design
6
Superclasses and Subclasses
In object-oriented terminology:
the existing class is typically described as
the base class, parent class, or superclass.
7
Superclasses and Subclasses
Inheritance examples:
8
Superclasses and Subclasses
9
Relationship between
Superclasses and Subclasses
“is a” relationship : is a correspondence
between levels
Examples:
(1) a house is a
building
Superclass:
building
Subclass: house
(2) a ranch is a
house.
Superclass: house
Subclass: ranch
10
The “extends” keyword
Syntax of java Inheritance:
class Subclass-name extends Superclass-name
{
//methods and fields
}
Employee
Salary: float
Programmer
bonus: int
12
Why use inheritance in java?
Method Overriding:
If subclass (child class) has the same method as declared in
the parent class, it is known as method overriding in Java.
In other words, it is used to provide the specific
implementation of a method which is already provided by
its superclass
Reusability:
is a mechanism which facilitates you to reuse the fields and
methods of the existing class when you create a new class.
You can use the same fields and methods already defined
in the previous class.
13
Example:
Java Program to demonstrate why we need method
overriding
hierarchical single
Class C
multilevel
15
Single Inheritance Example
16
Multilevel Inheritance Example
17
Hierarchical Inheritance
Example
I
18
References
19