Inheritance in C#
Inheritance in C#
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows you to create new classes (child classes or subclasses) based on existing classes (parent classes or superclasses). This promotes code reusability and establishes a hierarchical relationship between classes.
Key Concepts:
* Base Class (Parent Class):
* The class from which other classes inherit.
* Defines the common properties and behaviors that will be shared by its derived classes.
* Derived Class (Child Class):
* The class that inherits from a base class.
* Can add new properties and methods or override existing ones.
Inheritance Syntax:
public class BaseClass
{
// Properties and methods of the base class
}
public class DerivedClass : BaseClass
{
// New properties and methods specific to the derived class
}
Types of Inheritance:
* Single Inheritance:
* A derived class inherits from only one base class.
* This is the most common type of inheritance.
* Multiple Inheritance:
* A derived class inherits from multiple base classes.
* Not directly supported in C#. However, you can achieve similar behavior using interfaces.
* Multilevel Inheritance:
* A derived class inherits from a base class, which itself is derived from another base class.
* Creates a hierarchical structure.
* Hierarchical Inheritance:
* Multiple derived classes inherit from a single base class.
* Represents a tree-like structure.
Inheritance Keywords:
* base keyword: Used to access members of the base class from within a derived class.
* override keyword: Used to override a virtual or abstract method in a derived class.
* virtual keyword: Used to declare a method as virtual, allowing it to be overridden in derived classes.
* abstract keyword: Used to declare a class or method as abstract, meaning it cannot be instantiated directly.
Example:
public class Animal
{
public void Eat()
{
Console.WriteLine("Eating...");
}
}
public class Dog : Animal
{
public void Bark()
{
Console.WriteLine("Woof!");
}
}
public class Cat : Animal
{
public void Meow()
{
Console.WriteLine("Meow!");
}
}
In this example:
* Animal is the base class.
* Dog and Cat are derived classes that inherit from Animal.
* Both Dog and Cat can use the Eat() method from the base class.
* They also have their own specific methods (Bark() and Meow(), respectively).
Benefits of Inheritance:
* Code Reusability: Avoids redundant code by sharing common functionality.
* Polymorphism: Enables objects of different types to be treated as objects of a common base type.
* Extensibility: Allows for the creation of more specialized classes.
By understanding inheritance, you can design more efficient, flexible, and maintainable C# applications.
Would you like to delve deeper into a specific aspect of inheritance, such as polymorphism, abstract classes, or interfaces?
Comments
Post a Comment