Inheritance

OOP: Inheritance

Concept of Inheritance:

Inheritance is a fundamental concept in object-oriented programming where a class (known as the derived or child class) can inherit properties and behavior (methods) from another class (known as the base or parent class). This allows for code reusability and the creation of hierarchical relationships between classes.

Let's create and break down a program from the syntax which is provided on the OOP page:

cs Copy Code
using System;

class Animal {
    public void Eat() {
        Console.WriteLine("Eating...");
    }
}

class Dog : Animal {
    public void Bark() {
        Console.WriteLine("Woof!");
    }
}

class Program {
    static void Main(string[] args) {
        // Creating an instance of Dog
        Dog myDog = new Dog();

        // Accessing the Eat method which is inherited from Animal class
        myDog.Eat();  // Inherited from Animal

        // Accessing the Bark method which is specific to Dog class
        myDog.Bark();
    }
}
Output:
Eating...
Woof!

Explanation:

The 'Animal' class has a method 'Eat()' which simply prints "Eating..." to the console.

The 'Dog' class extends 'Animal' class using inheritance ('Dog : Animal'). It adds its specific behavior with a method 'Bark()' which prints "Woof!" to the console.

We then create an instance of 'Dog' called 'myDog' using the 'new' keyword.

We can call the 'Eat()' method on 'myDog' instance, even though it's not explicitly defined in the 'Dog' class. This is possible because Dog inherits the 'Eat()' method from its parent class, 'Animal'.

We can also call the 'Bark()' method, which is specific to the 'Dog' class and not inherited from the 'Animal' class.

Note: This demonstrates how inheritance allows us to reuse code and establish an "is-a" relationship, where a 'Dog' is a specific type of 'Animal' with additional behaviors.

What's Next?

We've now entered the finance section on this platform, where you can enhance your financial literacy.