Inheritance and Polymorphism
Inheritance and Polymorphism are fundamental concepts in Object-Oriented Programming (OOP) that enable code reusability, extensibility, and flexibility. They allow developers to model real-world relationships and create more robust and maintainable software.
Inheritance
Inheritance is a mechanism where a new class (called a derived class or subclass) inherits properties and behaviors (methods) from an existing class (called a base class or superclass). This promotes code reuse by allowing you to define a general class with common attributes and then create more specific classes that extend its functionality.
Key Concepts of Inheritance:
- Base Class (Superclass): The class whose properties are inherited.
- Derived Class (Subclass): The class that inherits properties from a base class.
- "Is-A" Relationship: Inheritance typically represents an "is-a" relationship. For example, a
Dog
is anAnimal
. - Code Reusability: Avoids redundant code by defining common logic in a base class.
- Extensibility: Allows adding new features to a derived class without modifying the base class.
Example: Vehicle Inheritance
Consider a base class Vehicle
with common properties like speed
and a method accelerate()
. We can then create derived classes like Car
and Bicycle
that inherit from Vehicle
and add their specific attributes and behaviors.
// Base Class
public class Vehicle {
public int Speed { get; set; }
public void Accelerate() {
Speed += 10;
Console.WriteLine($"Accelerating. Current speed: {Speed} km/h");
}
}
// Derived Class
public class Car : Vehicle {
public string Model { get; set; }
public void Honk() {
Console.WriteLine("Beep beep!");
}
}
// Another Derived Class
public class Bicycle : Vehicle {
public int Gear { get; set; }
public void ChangeGear(int newGear) {
Gear = newGear;
Console.WriteLine($"Gear changed to: {Gear}");
}
}
// Usage
var myCar = new Car { Model = "Sedan" };
myCar.Accelerate(); // Inherited from Vehicle
myCar.Honk(); // Specific to Car
var myBike = new Bicycle { Gear = 1 };
myBike.Accelerate(); // Inherited from Vehicle
myBike.ChangeGear(3); // Specific to Bicycle
Polymorphism
Polymorphism, meaning "many forms," allows objects of different classes to be treated as objects of a common base class. This enables a single interface to represent different underlying forms (data types). It significantly enhances flexibility and extensibility.
Types of Polymorphism:
- Compile-time Polymorphism (Static Polymorphism): Achieved through method overloading and operator overloading. The decision of which method/operator to call is made at compile time.
- Run-time Polymorphism (Dynamic Polymorphism): Achieved through method overriding (using virtual and override keywords in C#, or through virtual methods in Java). The decision of which method to call is made at runtime based on the actual object type.
Method Overriding:
Method overriding allows a derived class to provide a specific implementation of a method that is already provided by its base class. This is crucial for achieving runtime polymorphism.
Example: Polymorphic Behavior
Let's extend the Vehicle
example to demonstrate polymorphism.
// Base Class with a virtual method
public class Vehicle {
public virtual void Drive() {
Console.WriteLine("Driving a generic vehicle.");
}
}
// Derived Class
public class Car : Vehicle {
// Overriding the virtual method
public override void Drive() {
Console.WriteLine("Driving a car smoothly.");
}
}
// Another Derived Class
public class Truck : Vehicle {
// Overriding the virtual method
public override void Drive() {
Console.WriteLine("Driving a truck with heavy load.");
}
}
// Usage demonstrating polymorphism
public class Program {
public static void Main(string[] args) {
Vehicle myCar = new Car(); // Base class reference, derived object
Vehicle myTruck = new Truck(); // Base class reference, derived object
Vehicle genericVehicle = new Vehicle();
PerformAction(myCar); // Output: Driving a car smoothly.
PerformAction(myTruck); // Output: Driving a truck with heavy load.
PerformAction(genericVehicle); // Output: Driving a generic vehicle.
}
// A method that accepts a Vehicle object
public static void PerformAction(Vehicle vehicle) {
vehicle.Drive(); // The correct Drive() method is called at runtime
}
}
Note on Virtual and Override
In C#, the virtual
keyword in the base class method signifies that this method can be overridden by derived classes. The override
keyword in the derived class explicitly indicates that it is providing a new implementation for a base class method.
Tip for Polymorphism
Polymorphism allows you to write code that works with a collection of objects of different types, as long as they share a common base class or interface. This is powerful for creating adaptable and maintainable systems.
Benefits of Inheritance and Polymorphism
- Code Reusability: Reduces redundancy and development time.
- Maintainability: Changes in the base class are reflected in derived classes, simplifying updates.
- Extensibility: New functionality can be added easily by creating new derived classes.
- Flexibility: Polymorphism allows for dynamic behavior and adaptable code structures.
- Modularity: Promotes breaking down complex systems into smaller, manageable components.
Key Takeaway
Inheritance is about structuring class relationships and sharing code, while polymorphism is about treating objects of different types in a uniform way, leading to more flexible and dynamic applications.
Mastering inheritance and polymorphism is essential for building scalable and well-structured object-oriented applications.