What is Inheritance in OOP?
Inheritance is a fundamental principle of Object-Oriented Programming (OOP). It allows a class to acquire properties and methods from another class.
Inheritance = Reusing code by creating a new class from an existing class
Why Use Inheritance?
- ✔ Reuse existing code
- ✔ Reduce duplication
- ✔ Easier to maintain code
- ✔ Create hierarchical relationships
- ✔ Supports polymorphism
Real-Life Example
A Car is a type of Vehicle.
A car inherits all common features of a vehicle (like wheels and speed control) and adds its own features (like air conditioning and radio).
Vehicle → base class (parent)
Car → derived class (child)
C# Example of Inheritance
class Vehicle
{
public int Speed;
public void Move()
{
Console.WriteLine("Vehicle is moving");
}
}
class Car : Vehicle // Car inherits Vehicle
{
public string Color;
public void Honk()
{
Console.WriteLine("Car is honking");
}
}
Usage:
Car myCar = new Car();
myCar.Speed = 80; // inherited from Vehicle
myCar.Move(); // inherited method
myCar.Color = "Red"; // property from Car class
myCar.Honk(); // method from Car class
Key Points to Remember
- The child class inherits fields and methods from the parent class.
- The child class can add its own properties and methods.
- Supports method overriding using
virtualandoverride. - Helps in code reuse, structure, and polymorphism.
No comments:
Post a Comment