SalesforceBlue

Feel the rhythm of Salesforce

Apex

Apex Interfaces Simplified

Interfaces are like a contract which a class has to follow!

Consider you are creating a robot and you want that the robot should dance and sing. There could be different ways to dance and sing but these 2 things are mandatory for a robot to do. So all you should do is create an interface to achieve this!

Let’s see them in action:

public Interface Robot {
    void dance();
    void sing();
}

In the above block, we have created an interface Robot with only method declaration.

We haven’t defined the methods in it as it will be the class that implements this interface has the responsibility to define it.

public with sharing class MichaelJacksonRobot implements Robot {
    public void dance() {
        System.debug('Do break dance');
    }

    public void sing() {
        System.debug('Sing Thriller');
    }
}

In the above code block, we have implemented the Robot interface using the implements keyword.

It’s mandatory for the class which implements an interface to define all the methods which an interface has declared.

If any method is missed to be defined Apex compiler will throw an error.

Thank you for visiting SalesforceBlue.com
If you have any queries feel free to write down a comment below 🙂


Leave a Reply

Your email address will not be published. Required fields are marked *