Inheritance

Inheritance is a fundamental concept of object-oriented programming (OOP) that allows you to define a new class based on an existing class, inheriting its attributes and methods. The new class is called the derived class, and the existing class is called the base class or parent class. The derived class can add new attributes and methods, and modify the behavior of the inherited methods to suit its needs.

In C#, inheritance is achieved by using the : symbol followed by the name of the base class in the class definition of the derived class. Here is an example:

class Animal

{

    public void Eat()

    {

        Console.WriteLine("Eating...");

    }


    public void Sleep()

    {

        Console.WriteLine("Sleeping...");

    }

}


class Dog : Animal

{

    public void Bark()

    {

        Console.WriteLine("Barking...");

    }

}

In this example, the Animal class defines two methods, Eat() and Sleep(), that can be used by any derived class. The Dog class is derived from the Animal class and adds a new method, Bark().


When you create an object of the Dog class, it will have access to the Eat() and Sleep() methods inherited from the Animal class, as well as the Bark() method defined in the Dog class. Here is an example:


Dog myDog = new Dog();

myDog.Eat(); // Outputs "Eating..."

myDog.Sleep(); // Outputs "Sleeping..."

myDog.Bark(); // Outputs "Barking..."


Inheritance allows you to reuse existing code and build on top of it, making it easier to maintain and extend your code over time. By defining a base class with common functionality, you can create derived classes that specialize and add new functionality, without having to duplicate the common code. This can lead to more modular, flexible, and maintainable code.

Comments

Popular posts from this blog

OpenSolaris and Linux virtual memory and address space structures

Tagged architectures and multi-level UNIX

Tying top-down and bottom-up object and memory page lookups with the actual x86 page translation and segmentation