I want to understand polymorphism in c# so by trying out several constructs I came up with the following case:
class Shape
{
public virtual void Draw()
{
Console.WriteLine("Shape.Draw()");
}
}
class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Circle.Draw()");
}
}
I understand that in order to send the Draw() message to several related objects, so they can act according to its own implementation I must change the instance to which (in this case) shape is 'pointing' to:
Shape shape = new Circle();
shape.Draw(); //OK; This prints: Circle.Draw()
But why, when I do this:
Circle circle = new Circle();
circle.Draw(); //OK; This prints: Circle.Draw()
Shape shape = circle as Shape; // or Shape shape = (Shape)circle;
shape.Draw();
It prints: "Circle.Draw()"
Why it calls the Circle.Draw() instead Shape.Draw() after the cast? What is the reasoning for this?
There are two types of polymorphism which are the compile-time polymorphism (overload) and run-time polymorphism (overriding).
Types of Polymorphism in Oops In Object-Oriented Programming (OOPS) language, there are two types of polymorphism as below: Static Binding (or Compile time) Polymorphism, e.g., Method Overloading. Dynamic Binding (or Runtime) Polymorphism, e.g., Method overriding.
Type casting is when you assign a value of one primitive data type to another type. In Java, there are two types of casting: Widening Casting (automatically) - converting a smaller type to a larger type size. byte -> short -> char -> int -> long -> float -> double.
Polymorphism ( poly = many, morphe = form) is the ability to treat many different forms of an object as if they were the same. Polymorphism is achieved in C++ by using inheritance and virtual functions.
Casting does not change run-time type of object and what implementation of particular virtual method each instance have.
Note that following 2 cases you have as sample are identical:
Shape shape = new Circle();
shape.Draw(); //OK; This prints: Circle.Draw()
and:
Circle circle = new Circle();
Shape shape = circle as Shape;
shape.Draw();
The first one is essentially shorter version of the second.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With