Home > Back-end >  C# polymorphism - How to get the desired output
C# polymorphism - How to get the desired output

Time:09-28

I'm trying to understand polymorphism. In the below code, what is the best way to display all three texts without making changes to the main method and without adding any new methods?

using System;

class Program
    {
        public static void Main(string[] args)
        {
            Car c = new BMW();
            c.Start();
        }
    }

    public  class Car
    {
        
        public void Start()
        {
            Console.WriteLine("I am a Car");

        }

    }


    public class Luxury : Car
    {
        public void Start()
        {
            Console.WriteLine("I am a Luxury");
        }

    }


    public class BMW : Car
    {
        public void Start()
        {
            Console.WriteLine("I am a BMW");
        }

    }

CodePudding user response:

First, you made a mistake in your inheritance hierarchy. I'm guessing BMW should inherit from Luxury, not from Car:

public class BMW : Luxury

Once that's corrected, it sounds like you're looking for virtual methods. In the Car class make your method virtual:

public virtual void Start()
{
    Console.WriteLine("I am a Car");
}

This allows inheriting types to override that method. (Currently your inheriting types are obscuring or hiding that method, which even generates a compiler warning because that's almost always not what was intended.) For example:

public override void Start()
{
    Console.WriteLine("I am a Luxury");
}

This override essentially replaces the parent method, but it can also call the parent method to effectively "combine" the two:

public override void Start()
{
    base.Start();
    Console.WriteLine("I am a Luxury");
}

If you continue this pattern down the inheritance hierarchy, then invoking the method on the BMW type would first invoke it on the Luxury type and then print its own message. And invoking the method on the Luxury type would first invoke it on the Car type and then print its message.

  • Related