Introduction
Inheritance is a fundamental concept in object-oriented programming. It allows you to create new classes that inherit properties and methods from existing classes, promoting code reusability and organization.
Key benefits: Reusability, Maintainability, Polymorphism (many forms of the same thing).
Key Concepts
- Base Class (Parent Class): The class that provides the initial properties and methods.
- Derived Class (Child Class): Inherits properties and methods from the base class.
- Method Overriding: A derived class provides its own implementation of a method inherited from the base class.
- Polymorphism: The ability of objects of different classes to respond to the same method call in different ways.
Examples
Let's illustrate with a simple example:
public class Animal
{
public string name;
public Animal(string name)
{
this.name = name;
}
}
class Dog : Animal
{
public string breed;
public Dog(string name, string breed)
{
this.name = name;
this.breed = breed;
}
}
class Cat : Animal
{
public string color;
public Cat(string name, string color)
{
this.name = name;
this.color = color;
}
}
Animal inherits from Animal. Dog inherits from Animal, and Cat from Animal. Each inherits the name and color.