In the code snippet above i have a base class Shape and two derived classes from it Rectangle
and Triangle
. I instantiate them but for the one Triangle
object I use reference type of his base class.
So now when I call a method calculate()
it will prefer to call the method that is taking the base class argument.
What is the purpose of this?
I am creating Triangle
object not Shape
object I just use the reference of the base class. And my other question is are they any other differences from using the reference of the base class and instantiating the object from the derived instead of using derived reference?
public static void Main(string[] args)
{
Point tc = new Point(3, 4);
Point rc = new Point(7, 5);
Shape shape = new Triangle(tc, 4, 4, 4);
calculate(shape);
}
public static void calculate(Shape shape) <<-- new Triangle() with base class ref will came here.
{
Console.WriteLine("shape");
}
public static void calculate(Rectangle rectangle)
{
Console.WriteLine("rectangle");
}
public static void calculate(Triangle triangle) <<-- new Triangle() using triangle ref will came here.
{
Console.WriteLine("triangle");
}