In object-oriented programming (OOP), inheritance is a basic notion that allows a class (called the derived class) to inherit the characteristics and behaviours of another class (called the base class). Inheritance allows the derived class to reuse, extend, and alter the base class’s features and behaviours, resulting in more efficient and modular code.
Here’s an example of inheritance in action in C#:
// Define the base class public class Employee { public string Name { get; set; } public int Age { get; set; } public void Break() { Console.WriteLine("Break Time..."); } public void Work() { Console.WriteLine("Work Time..."); } } // Define the derived class public class FirstEmployee : Employee { // The FirstEmployee class inherits the Name and Age properties and the Break and Work methods from the Employee class // Define a new method specific to the FirstEmployee class public void WorkLoad() { Console.WriteLine("WorkLoad"); } } //Defined an another Derived class public class SecondEmployee: Employee { // The SecondEmployee class also inherits the Name and Age properties and the Break and Work methods from the Employee class // Define a new method specific to the SecondEmployee class public void Leave() { Console.WriteLine("Leave..."); } }
The FirstEmployee & SecondEmployee class is derived from the Employee class in this example, and hence inherits all of its characteristics and behaviors. Leave & WorkLoad is a new method defined by the FirstEmployee & SecondEmployee class that is exclusive to the derived class.
You may then construct derived classes for specific sorts of Employees, such as FirstEmployee, Tiger, and Lion, that inherit the Employee class’s characteristics and behaviors while adding any extra attributes and behaviors unique to that type of Employee.
In object-oriented programming, inheritance is a strong idea that allows for code reuse, modularity, and extension. It is a crucial topic in OOPS. The common characteristics and behaviors of all animals are described in the basic Animal class and may be inherited and shared by the derived classes, allowing for code reuse and modularity. It also provides for expansion because additional animal kinds may be simply added to the hierarchy by specifying new derived classes.