C# Language
Concept of Polymorphism:
Polymorphism in OOP refers to the ability of objects to be treated as instances of their parent class while retaining their own specialized behavior. This allows you to work with objects of different derived classes through a common interface.
⤏ As per provided syntax on the OOP page, we have a base class 'Shape' with a virtual method 'Draw()'. This method is overridden in the derived classes 'Circle' and 'Rectangle'. When we create an instance of 'Circle' or 'Rectangle' and assign it to a variable of type 'Shape', polymorphism comes into play.
• Let's break down the syntax:
class Shape { public virtual void Draw() { Console.WriteLine("Drawing a shape..."); } }
⤏ This is the base class 'Shape'. It has a virtual method 'Draw()' that is meant to be overridden by derived classes.
class Circle : Shape { public override void Draw() { Console.WriteLine("Drawing a circle..."); } }
⤏ 'Circle' is a derived class of 'Shape' and it overrides the 'Draw()' method to draw a circle.
class Rectangle : Shape { public override void Draw() { Console.WriteLine("Drawing a rectangle..."); } }
⤏ 'Rectangle' is another derived class of Shape and it overrides the 'Draw()' method to draw a rectangle.
Shape shape = new Circle(); shape.Draw(); // Output: Drawing a circle
⤏ Here, we create an instance of 'Circle' and assign it to a variable of type 'Shape'. Even though the variable is of type 'Shape', the actual object is a 'Circle'. When we call 'Draw()' on this variable, the overridden 'Draw()' method of 'Circle' is executed, printing "Drawing a circle..."
shape = new Rectangle(); shape.Draw(); // Output: Drawing a rectangle
⤏ Now, we create an instance of 'Rectangle' and assign it to the same variable 'shape', which is of type 'Shape'. When we call 'Draw()' again, it executes the overridden 'Draw()' method of 'Rectangle', printing "Drawing a rectangle..."
• It's time to create a complete program:
using System; class Shape { public virtual void Draw() { Console.WriteLine("Drawing a shape..."); } } class Circle : Shape { public override void Draw() { Console.WriteLine("Drawing a circle..."); } } class Rectangle : Shape { public override void Draw() { Console.WriteLine("Drawing a rectangle..."); } } class Program { static void Main(string[] args) { Shape shape = new Circle(); shape.Draw(); // Output: Drawing a circle shape = new Rectangle(); shape.Draw(); // Output: Drawing a rectangle } }
Drawing a circle... Drawing a rectangle...
Note: This behavior demonstrates polymorphism in action, where the method call is resolved dynamically at runtime based on the actual type of the object.
What's Next?
We've now entered the finance section on this platform, where you can enhance your financial literacy.