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?