What is Inheritance? When to use Inheritance?

Inheritance is creating a PARENT-CHILD relationship between two classes, where child class will automatically get the properties and methods of the parent.

Inheritance is good for: REUSABILITY and ABSTRACTION of code

Inheritance is a fundamental concept in object-oriented programming (OOP) where one class (child or derived class) can acquire properties and behaviors (methods and fields) from another class (parent or base class). The child class inherits the characteristics of the parent class, allowing for code reuse and establishing a hierarchical relationship among classes.

In C#, you can implement inheritance using the : (colon) symbol to specify the base class from which the child class derives. The child class then inherits all the public and protected members of the base class.

Here's an example of inheritance in C#:

// Base class public class Animal { public string Name { get; set; } public void Speak() { Console.WriteLine("Animal speaks."); } } // Derived class inheriting from Animal public class Dog : Animal { public void Bark() { Console.WriteLine("Woof! Woof!"); } }

In this example, the Animal class serves as the base class, and the Dog class is the derived class. The Dog class inherits the Name property and the Speak() method from the Animal class.


 

Post a Comment

Previous Post Next Post