1. Object – Oriented Programming
Week 11 &12 – Inheritance
Ferdin Joe John Joseph, PhD
Faculty of Information Technology
Thai-Nichi Institute of Technology
7. Concept of Inheritance
• What is inheritance?
- to inherit properties/capabilities (member
data and member functions) from an
existing class or existing classes.
- the existing class is called as a base class
- the inherited class is called as a derived
class
- The two classes in the inheritance must
have relationship in terms of code-reusable
8. Concept of Inheritance
(continue)
• Why Inheritance?
- code reusability (save time and money)
- Increasing program reliability
- Better problem-solving and program
design
- Supporting polymorphism
9. Concept of Inheritance
(continue)
• Conceptual examples
- example 1:
circle
base class: circle
area = 3.1415*r*r
derived class: sphere
sphere
area = 4 *circle::area
volume = 4/3*circle::area*r
r
r
10. Base Classes and Derived
Classes
• Characteristics of a base class
- has all features of the objects in the category
- is a general description of all objects in the
category in terms of member data and member
functions
• Characteristics of a derived class
- has detailed and specific features of the objects
in the class
- usually has more capabilities than the base class
in terms of member data and member functions
• Examples:
- circle sphere employee manager
11. Types of Inheritance
• Basically, there are three types of
inheritance
- simple inheritance: a base class derives
on or many derived classes
- multi-level inheritance: a derived class
can be served as a base class for next
level of inheritance
- multiple inheritance: there are more
than one base class to derive one or
many derived classess.
15. Example
public class Door {
public void open ()
{
push(); // Since this is just a generic "Door" we will assume the simplest
opening method.
// The actual open method must be overridden by a subclass, as
we see below.
// Later, a way to force a subclass to override a method will be
demonstrated --
// but for this simple example will do for now.
}
}
Faculty of Information Technology,
Thai-Nichi Institute of Technology
15
16. Example
class BankVaultDoor extends Door { // The "extends" keyword used to tell
java that BankVaultDoor inherits the functionality of Door.
public void open () {
enterCombination();
pull;
}
}
Faculty of Information Technology,
Thai-Nichi Institute of Technology
16
17. Example
public class Main {
public static void main(String[] args) {
Door d1 = new BankVaultDoor();
Door d2 = new HouseFrontDoor();
Door d3 = new CarDoor();
}
if (arg[0] == "car") {
d3.open();
} else if (arg[0] == "bank") {
d1.open();
} else {
d2.open();
}
}
Faculty of Information Technology,
Thai-Nichi Institute of Technology
17