Professional Documents
Culture Documents
Inheritance:
Inheritance is the concept of a child class (Sub
class) automatically inheriting the variables and
methods defined in a parent class (Super class) .
It is one of the primary features of Object
Oriented Programming.
Benefits:
The primary benefit of inheritance is
reusability.
Once a behavior is defined in a super class, that
behavior is automatically inherited by all its
subclasses and reused.
So developers need not redevelop the logic
again.
Real time Example:
Brad wrote a class for each of the three shapes
Square
Rotate() {
// code to
rotate a square
}
playSound() {
//code to play
the amv file for
square
}
Circle
Rotate() {
// code to
rotate a Circle
}
playSound() {
//code to
play the amv
file for Circle
}
Triangle
Rotate() {
// code to rotate a triangle
}
playSound() {
//code to play the amv file for triangle
}
Implementation:
I found a flaw in Brads approach and Brad got
duplicated code! The rotate procedure is in all
four shape things.
How OO inheritance works, to avoid duplicated
code.
1. I looked at what all three classes have in
common.
Square
rotate()
playSound()
Circle
rotate()
playSound()
Triangle
rotate()
playSound()
2. They are shapes, and they all rotate and
playSound.
Shape
rotate()
playSound()
3. Then I linked the other three shape classes to
the new
Shape class, in a relationship called
inheritance.
Shape
rotate()
playSound()
Squar
e
Circle
Triang
le