baudi27
baudi27

Reputation: 25

While Upcasting I called method of base class(with virtual keyword) but after upcasting its calling override method from derived class

I am trying to understand Upcasting and DownCasting. In the code shown below, I upcast Circle object to Shape and after upcasting methods available are Draw and Duplicate, but when I executed shape.Draw() it is showing output from derived class - can anybody explain why?

class Program
{
    static void Main(string[] args)
    {
        //Use Base class reference
        Circle circle = new Circle();
        //Up-casting
        Shape shape = circle;
        shape.Draw();           //output:- Drawing a Circle 
        shape.duplicate();      //output:- Duplicated!!    
    }
}

class Shape
{
    //Draw()available to base class Shape and all child classes
    public virtual void Draw()
    {
        Console.WriteLine("Drawing Shape");
    }

    public void duplicate()
    {
        Console.WriteLine("Duplicated!!");
    }
}

class Circle : Shape
{
   
    public override void Draw()
    {
        Console.WriteLine("Drawing a Circle ");
    }

    //Speciallized method available to only Circle class
    public void FillCircle()
    {
        Console.WriteLine("Filling a Circle");
    }
}

Why is the output of shape.Draw(); "Drawing a Circle" instead of "Drawing Shape" even though upcasting doesn't make access to any method from child class?

Upvotes: -1

Views: 475

Answers (1)

cly
cly

Reputation: 708

The Draw method declared as virtual in Shape which means the runtime will look for overriding member on actual instance and execute it if found. It doesnt care what is the type of the reference you currently have to that instance.

Of course you wont see any Circle specific members while trying to call them using reference of type Shape.

Upvotes: 0

Related Questions