CSharp - Polymorphism: Base Class reference to Child Class Object Demo

Introduction

Polymorphism is generally associated with one method name with multiple forms/constructs.

Demo

using System;

class Vehicle/*from   ww w . j a  v a 2  s  . c o  m*/
{
    public void ShowMe()
    {
        Console.WriteLine("Inside Vehicle.ShowMe");
    }
}
class Bus : Vehicle
{
    public void ShowMe()
    {
        Console.WriteLine("Inside Bus.ShowMe");
    }
    public void BusSpecificMethod()
    {
        Console.WriteLine("Inside Bus.ShowMe");
    }
}

class Program
{
    static void Main(string[] args)
    {

        Vehicle obVehicle = new Bus();
        obVehicle.ShowMe();//Inside Vehicle.ShowMe
                           // obVehicle.BusSpecificMethod();//Error
                           //Bus obBus = new Vehicle();//Error
    }
}

Result

Analysis

For the following two lines of codes in the preceding program:

Vehicle obVehicle = new Bus();
obVehicle.ShowMe();

In the code above we are pointing to a derived class object (Bus object) through a parent class reference (Vehicle reference).

Then we are invoking the ShowMe() method.

This way of invoking is allowed: a base class reference can point to a derived class object.

But we cannot use either of these lines:

obVehicle.BusSpecificMethod();//Error

Since the type here is Vehicle not Bus.

To remove this error, you need to downcast, as follows:

((Bus)obVehicle).BusSpecificMethod();

The following line of code has compile time error

Bus obBus = new Vehicle();//Error

To remove this error, you need to downcast, as follows:

Bus obBus = (Bus)new Vehicle();

Note

Through a parent class reference, we can refer to a child class object but the reverse is not true.

An object reference can implicitly upcast to base class reference and explicitly downcast to a derived class reference.

Related Topic