Inheritance
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class to inherit the properties and methods of another class. This enables the creation of new classes that are specialized versions of existing classes, promoting code reusability and extensibility.
Inheritance Terminology
Types of Inheritance
Example: Animal Class Hierarchy
Consider an Animal class representing common animal characteristics:
class Animal {
// Fields
private string name;
private int age;
private string species;
// Methods
public void Eat() {
Console.WriteLine("Animal is eating.");
}
public void Sleep() {
Console.WriteLine("Animal is sleeping.");
}
}
Derived Classes: Dog and Cat
Create a Dog class that inherits from the Animal class:
class Dog : Animal {
// Methods
public void Bark() {
Console.WriteLine("Dog is barking.");
}
}
Create a Cat class that also inherits from the Animal class:
class Cat : Animal {
// Methods
public void Purr() {
Console.WriteLine("Cat is purring.");
}
}
Inheritance Benefits
Conclusion
Inheritance is a powerful and versatile tool in C# programming that allows programmers to create specialized classes that inherit properties and methods from existing classes. It plays a crucial role in OOP principles, enabling code reusability, extensibility, and code organization. Understanding inheritance is essential for developing effective and maintainable C# applications.