Inheritance
Introduction to Inheritance
Inheritance is a key feature of object-oriented programming in .NET that allows one class (derived class) to inherit properties and behavior from another class (base class). It promotes code reuse and enhances the structure and organization of code.
Key Concepts
- Base Class: Also known as parent class or superclass, it serves as the foundation for derived classes.
- Derived Class: Also known as child class or subclass, it inherits properties and methods from the base class.
- Derived Class Extension: A derived class can extend the functionality of the base class by adding new methods or overriding existing ones.
Example: Basic Inheritance
Here's a simple example demonstrating inheritance in C#:
// Base class (parent class)
public class Animal
{
public void Eat()
{
Console.WriteLine("Animal is eating.");
}
}
// Derived class (child class)
public class Dog : Animal
{
public void Bark()
{
Console.WriteLine("Dog is barking.");
}
}
// Usage
Dog myDog = new Dog();
myDog.Eat(); // Inherited method
myDog.Bark(); // Method of derived class
In this example, Dog
inherits the Eat()
method from Animal
and adds its own method Bark()
.
Overriding Methods
Derived classes can override methods of the base class to provide specific implementations.
Example: Method Overriding
Override a method in the derived class:
// Base class
public class Shape
{
public virtual void Draw()
{
Console.WriteLine("Drawing shape.");
}
}
// Derived class
public class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing circle.");
}
}
// Usage
Shape shape = new Circle();
shape.Draw(); // Output: Drawing circle.
In this example, Circle
overrides the Draw()
method inherited from Shape
to draw a circle specifically.
Base Keyword
The base
keyword is used to access members of the base class from within a derived class.
Example: Using the base Keyword
Accessing base class members:
// Base class
public class Vehicle
{
public void Start()
{
Console.WriteLine("Vehicle started.");
}
}
// Derived class
public class Car : Vehicle
{
public void Start()
{
base.Start(); // Call base class method
Console.WriteLine("Car started.");
}
}
// Usage
Car myCar = new Car();
myCar.Start(); // Output: Vehicle started. Car started.
In this example, Car
uses base.Start()
to call the Start()
method of Vehicle
before executing its own logic.
Conclusion
Inheritance is a powerful concept in .NET that facilitates code reuse and promotes hierarchical organization of classes. Understanding inheritance helps developers create more efficient and maintainable code.