Inheritance (Exercise) – Learn C#

1  comments

When you look into a dictionary, the verb inherit means to derive a quality from parents or ancestors. You know, your mom was tall, your dad was tall and you are likely to be tall too. This is exactly what inheritance does even in programming! It’s nothing scary, just instead of a child who inherits the traits of its parents, you have a subclass which inherits members from its base class.

This is an exercise for this YouTube video.

Happy learning and good luck!

 

[qsm quiz=9]

 

Assignment: Create an Animal class with one method for making sound. Then create a Dog and a Cat (which derive from Animal) and make them bark or meow respectively.

Click to see the answer
class Animal
{
    public virtual void MakeSound()
    {
        Console.WriteLine("generic animal sound");
    }
}

class Dog : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("woof");
    }
}

class Cat : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("meow");
    }
}

 

 

 

 

About the author 

Matt Rešetár

Matt is an app developer with a knack for teaching others. Working as a freelancer and most importantly developer educator, he is set on helping other people succeed in their Flutter app development career.

You may also like

  • {"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}
    >