0
0
C Sharp (C#)programming~30 mins

Runtime polymorphism execution in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Runtime Polymorphism Execution
📖 Scenario: Imagine you are creating a simple program to show how different animals make sounds. Each animal has its own way of making a sound, but you want to use the same method name to call their sounds. This is called runtime polymorphism.
🎯 Goal: You will build a program with a base class Animal and two derived classes Dog and Cat. Each derived class will have its own version of the MakeSound method. You will then create a list of animals and call MakeSound on each one to see the different sounds.
📋 What You'll Learn
Create a base class called Animal with a virtual method MakeSound.
Create two derived classes called Dog and Cat that override MakeSound.
Create a list of Animal objects containing both Dog and Cat instances.
Use a foreach loop to call MakeSound on each animal and print the result.
💡 Why This Matters
🌍 Real World
Runtime polymorphism is used in many programs to handle different objects with a common interface, like different shapes in a drawing app or different payment methods in a shopping app.
💼 Career
Understanding runtime polymorphism is essential for object-oriented programming jobs, as it helps write flexible and reusable code.
Progress0 / 4 steps
1
Create the base class Animal
Create a public class called Animal with a public virtual method MakeSound that returns a string "Some sound".
C Sharp (C#)
Need a hint?

Use the virtual keyword to allow derived classes to override the MakeSound method.

2
Create derived classes Dog and Cat
Create two public classes called Dog and Cat that inherit from Animal. Override the MakeSound method in Dog to return "Bark" and in Cat to return "Meow".
C Sharp (C#)
Need a hint?

Use the override keyword to provide a new version of MakeSound in each derived class.

3
Create a list of animals
Create a List<Animal> called animals and add one Dog object and one Cat object to it.
C Sharp (C#)
Need a hint?

Remember to include using System.Collections.Generic; at the top for the list.

4
Call MakeSound on each animal and print
Use a foreach loop with variable animal to go through animals and print the result of animal.MakeSound().
C Sharp (C#)
Need a hint?

Use Console.WriteLine(animal.MakeSound()) inside the foreach loop.