Introduction

In an inheritance chain, we can cast either from the bottom to the top or in the reverse direction.

In upcasting, we get a base class reference from a child class reference; with downcasting, we do the reverse.

A parent class reference can point to a child class object; we can write something like

Player myPlayer=new Footballer();

We are assuming that Player class is the base class and the Footballer class is derived from that.

This is in the direction of upcasting which is simple and implicit.

When we create a base reference from a child class reference, that base class reference can have a more restrictive view on the child object.

Demo

using System;
class Shape//from  ww  w .j a  va  2  s .c om
{
    public void ShowMe()
    {
        Console.WriteLine("Shape.ShowMe");
    }
}
class Circle : Shape
{
    public void Area()
    {
        Console.WriteLine("Circle.Area");
    }
}
class Rectangle : Shape
{
    public void Area()
    {
        Console.WriteLine("Rectangle.Area");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("***Upcasting Example***\n");
        Circle circleOb = new Circle();
        //Shape shapeOb = new Circle();//upcasting
        Shape shapeOb = circleOb;//Upcasting
        shapeOb.ShowMe();
        //shapeOb.Area();//Error
        circleOb.Area();//ok
    }
}

Result

Analysis

We have implemented upcasting using these lines of code:

Shape shapeOb = circleOb;//Upcasting
shapeOb.ShowMe();

Although both shapeOb and circleOb point to the same object, shapeOb doesn't have access to the Area() method of circle.

The following is downcasting.

Circle circleOb2 = (Circle)shapeOb;//Downcast

The code above are creating a subclass reference from a base class reference.

Downcasting is explicit and unsafe.

Related Topic