Introduction to Inheritance

Rumman Ansari   Software Engineer   2019-07-16   5896 Share
☰ Table of Contents

Table of Content:


Inheritance enables you to create a new class that reuses, extends, and modifies the behavior that is defined in another class. The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class.

Syntax

Example:
class DerivedClass:BaseClass
{
}

Problem Scenario

Create a Base Class called animal and inherit the same into child classes like Cat, Dog and Human

Approach to solve the problem

  • Step 1: Create a Base Class called Animal.
  • Step 2: Create child classes like Dog, Cat, and Human that inherits from Animal
  • Step 3: In the main method create a reference for Animal and instantiate the reference against Cat, Dog, and Human classes.

Solution


public class Animal
{
	public string Name { get; set; }
	public string Type { get; set; }
	public virtual string Speak()
	{
		return string.Empty;
	}
}

public class Human : Animal
{
	public Human()
	{
		Type = "Human"; // Type property is inherited from base class Animal
	}
	
	public override string Speak()
	{
		return "My Name is " + Name; // Name property is inherited from base class Animal
	}
}

public class Dog : Animal
{
	public Dog()
	{
		Type = "Dog";// Type property is inherited from base class Animal
	}
	
	public override string Speak()
	{
		return "BOW...";
	}
}

public class Cat : Animal
{
	public Cat()	
	{
		Type = "Cat";// Type property is inherited from base class Animal
	}
	public override string Speak()
	{
		return "Meow...";
	}
}

class Program
{
static void Main(string[] args)
{
	Animal Animal = new Cat();
	Animal.Speak();
	Animal = new Dog();
	Animal.Speak();
	Animal = new Human();
	Animal.Speak();
	}
}

Explanation about the solution

A base class Animal has been created with a virtual method Speak(). From the Animal base class, the child classes : Dog, Cat and Human are created. In each of these classes, the method Speak is overrided and a different implementation has been provided. Override is a dynamic polymorphism concept which is explained under polymorphism. The public properties Name and Type are also getting inherited from the parent base class Animal and it can be used inside the child class.

The above program says that Cat is an Animal, Dog is an Animal and Human is an Animal. The derived class is of type base class. All the child objects created are derived from a Base Class Animal.