Chapter 3 Inheritance.
Chapter 3 Inheritance.
Programming
CHAPTER - 3
Inheritanc
e
Objective
s
After studying this chapter, students should be able to learn:
Basics of Inheritance
Types of Inheritance
Aggregation
Review Questions
Inheritanc
e
Object-oriented programming (OOP) is popular because:
• It enables reuse of previous code saved as classes
All Java classes are arranged in a hierarchy
• Object is the superclass of all Java classes
Inheritance and hierarchical organization capture idea:
• One thing is a refinement or extension of another
Reusability - building new classes by utilizing existing classes.
Inheritanc
e
It is always good/“productive” if we are able to reuse something that is
already exists rather than creating the same all over again.
This is achieved by creating new classes, reusing the data members and
methods of existing classes.
This mechanism of deriving a new class from existing/old class is called
“inheritance”.
The old class is known as “base” class, “super” class or “parent” class”;
and the new class is known as “sub” class, “derived” class, or “child”
class.
Inheritanc
e
Parent
Inherited capability
Child
Inheritanc
e
superclass = parent class OR base class
subclass = child class OR derived class
Example Cont.
Inheritanc
…
e
Inheritanc
e
Inheritance relationships often are shown graphically in a UML class
diagram, with an arrow with an open arrow head pointing to the parent
class.
Vehicle
Car
Example
Declaring sub
classes
subclass superclass
or extends or
derived class base class
Inheritance -
Declaring Sub
example
classes
Types of
inheritance
The different types of inheritances are:
• Single inheritance (only one super class)
B C B C D
(a) Single Inheritance (b) Multiple Inheritance (c) Hierarchical Inheritance
A A A
B C B C
B
C D D
(d) Multi-Level Inheritance (e) Hybrid Inheritance (f) Multipath Inheritance
Single inheritance
example
Single inheritance example (cont
…)
Single inheritance example (cont
…)
output
Multilevel Inheritance
example
Multilevel Inheritance
example(cont…)
output
Multiple
inheritance
Multiple inheritance allows a class to be derived from two or more
classes, inheriting the members of all parents
Collisions, such as the same variable name in two parents, have to
be
resolved
Java does not support multiple inheritance
In most cases, the use of interfaces gives us aspects of multiple
inheritance without the overhead.
The protected
modifier
polymorphism.
Here the compiler knows which method is called at the