I've just coded this in C# to try and understand what's happening when you downcast/upcast an instance of a class.
Class1.cs
using System;
public class Shapes
{
protected int _x;
protected int _y;
public Shapes()
{
_x = 0;
_y = 0;
}
public virtual void Printing()
{
Console.WriteLine("In Shapes");
}
}
public class Circle: Shapes
{
public override void Printing()
{
Console.WriteLine("In Circle");
}
}
public class Square : Shapes
{
public new void Printing()
{
Console.WriteLine("In Square");
}
}
------------------------------------------------------------------------------------------
And now to Program.cs
using System;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
Shapes test1 = new Shapes();
Circle test2 = (new Circle());
Square test3 = new Square();
test1.Printing(); //In Shapes
test2.Printing(); //In Circle
test3.Printing(); //In Square
Console.WriteLine("------");
Shapes test4 = test2;
Shapes test5 = test3;
test4.Printing(); //In Circle (?)
test5.Printing(); //In Shapes (Ok)
Console.WriteLine("------");
Circle test6 = (Circle)test4;
Square test7 = (Square)test5;
test6.Printing(); //In Circle
test7.Printing(); //In Square
Console.WriteLine("------");
Square test10 = (Square)test4; //System.InvalidCastException: 'Unable to cast object of type 'Circle' to type 'Square'.'
Console.ReadLine();
}
}
}
So the questions are:
Can someone explain what's happening when I upcast then downcast?
Why does test4 print "In circles" when I've made it into back into a base class?
After test4 has been made into a Shape, why can't it go back down into Square (test10)?