Thursday, April 13, 2023

Polymorphism in Apex Programming with Example

Polymorphism is a concept in object-oriented programming where a single method or function can be used to perform different operations based on the type of object that it is called on. In Apex, polymorphism can be achieved using interfaces, abstract classes, and virtual methods. Here's an example of polymorphism in Apex using interfaces:

// Define an interface
public interface Shape {
    void draw();
}


// Define classes that implement the Shape interface
public class Circle implements Shape {
    public void draw() {
        System.debug('Drawing a circle');
    }
}


public class Rectangle implements Shape {
    public void draw() {
        System.debug('Drawing a rectangle');
    }
}


// Call the draw method on different objects of type Shape
Shape s1 = new Circle();
Shape s2 = new Rectangle();
s1.draw(); // Output: Drawing a circle
s2.draw(); // Output: Drawing a rectangle

In the above example, we define an interface called Shape with a method called draw(). We then define two classes, Circle and Rectangle, that implement the Shape interface and provide their own implementation of the draw() method.

Finally, we create two objects of type Shape, one of type Circle and one of type Rectangle. When we call the draw() method on each of these objects, the appropriate implementation of the draw() method is called based on the type of the object, demonstrating polymorphism.


Let me know your thoughts in the comment section!!

No comments:

Post a Comment

Mostly Viewed