⬅ Previous Topic
Abstraction in Programming - OOPNext Topic ⮕
Polymorphism in Programming - OOP⬅ Previous Topic
Abstraction in Programming - OOPNext Topic ⮕
Polymorphism in Programming - OOPInheritance is one of the fundamental principles of Object-Oriented Programming (OOP). It allows a class (called the child class or subclass) to acquire the properties and behaviors (methods) of another class (called the parent class or superclass).
This means you can create new classes based on existing ones, avoiding code duplication and promoting reusability. Inheritance supports the idea of hierarchical classification — just like in the real world, where a "Dog" is a type of "Animal".
Imagine a blueprint for a general Vehicle that has properties like speed
and methods like move()
. Now suppose you want to define a Car. Instead of defining everything from scratch, you can let the Car
class inherit the properties and methods from Vehicle
, and add specific ones like openTrunk()
.
CLASS Vehicle
METHOD move()
PRINT "The vehicle is moving"
CLASS Car EXTENDS Vehicle
METHOD openTrunk()
PRINT "Trunk is now open"
// Create an object of Car
car1 = NEW Car()
car1.move() // Inherited from Vehicle
car1.openTrunk() // Specific to Car
Output:
The vehicle is moving Trunk is now open
The Car
class inherits the move()
method from Vehicle
. So when you create an object of Car
, it can use both the inherited method move()
and its own method openTrunk()
.
What happens if both parent and child define a method with the same name?
Answer: The method in the child class will override the method from the parent class. This is called method overriding, and it's useful when the child needs a different behavior.
CLASS Animal
METHOD speak()
PRINT "Animal makes a sound"
CLASS Dog EXTENDS Animal
METHOD speak()
PRINT "Dog barks"
// Create object
pet = NEW Dog()
pet.speak()
Output:
Dog barks
This demonstrates that the Dog
class has overridden the speak()
method of its parent Animal
.
Inheritance can also be extended across multiple levels:
CLASS LivingBeing
METHOD breathe()
PRINT "Breathing..."
CLASS Animal EXTENDS LivingBeing
METHOD move()
PRINT "Animal moves"
CLASS Fish EXTENDS Animal
METHOD swim()
PRINT "Fish swims"
// Create object
fish1 = NEW Fish()
fish1.breathe()
fish1.move()
fish1.swim()
Output:
Breathing... Animal moves Fish swims
Can a child class access all properties of its parent?
Answer: Yes, except for private properties/methods which are not accessible directly. However, protected and public members are inherited.
⬅ Previous Topic
Abstraction in Programming - OOPNext Topic ⮕
Polymorphism in Programming - OOPYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.