Polymorphism

 Polymorphism


Polymorphism is the ability of an object to take on many forms. In OOP, polymorphism is achieved through method overriding and method overloading.


Here's an example of polymorphism in C#:



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() {

public override void Draw() {

Console.WriteLine("Drawing a rectangle");

}

}




In this example, we define a base class called `Shape` that has a `Draw` method. We then define two derived classes called `Circle` and `Rectangle` that override the `Draw` method to draw specific shapes. We can then create instances of these classes and call the `Draw` method, which will behave differently depending on the type of object being called.


Method overloading is another form of polymorphism where a class can have multiple methods with the same name but different parameters. Here's an example in Java:


```java

public class MathUtils {

    public int add(int a, int b) {

        return a + b;

    }


    public double add(double a, double b) {

        return a + b;

    }

}

In this example, we define a class called MathUtils that has two add methods with different parameter types. We can then call these methods with different arguments, and the appropriate method will be called based on the argument types.


Overall, OOP provides a powerful and flexible way to organize code into reusable and extensible objects. By following the principles of abstraction, encapsulation, inheritance, and polymorphism, we can create robust and maintainable software systems.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...