Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymorphism and casting

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?

like image 403
user3105717 Avatar asked Apr 14 '14 23:04

user3105717


People also ask

What are two types of polymorphisms?

There are two types of polymorphism which are the compile-time polymorphism (overload) and run-time polymorphism (overriding).

What are the polymorphism techniques?

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.

What is casting in Java?

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.

What is polymorphic behavior?

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.


1 Answers

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.

like image 173
Alexei Levenkov Avatar answered Sep 30 '22 02:09

Alexei Levenkov