Search Here

Apex Interface datatype

 In Apex, an interface is a blueprint for a class, defining a set of methods that a class must implement.

 An interface defines a contract that a class must adhere to, specifying the method signatures (names, 

return types, and parameter lists) that the class must provide.


Interfaces are used to establish a common set of behaviors that multiple classes can implement. 

This allows for polymorphism, where objects of different classes that implement the same interface can 

be treated as objects of that interface type, providing a way to work with various objects in a 

consistent manner.


// Define an interface named Printable

public interface Printable {

    void print(); // Interface method signature

}


// Implement the Printable interface in a class

public class Printer implements Printable {

    public void print() {

        System.debug('Printing a document...');

    }

}


public class Screen implements Printable {

    public void print() {

        System.debug('Displaying a message on the screen...');

    }

}


public class InterfaceExample {

    public static void main() {

        // Create objects of different classes that implement Printable

        Printable documentPrinter = new Printer();

        Printable screenDisplay = new Screen();


        // Call the print method on each object

        documentPrinter.print(); // Prints using the Printer class

        screenDisplay.print();    // Displays using the Screen class

    }

}


We define an interface named Printable with a single method print().


We implement the Printable interface in two classes, Printer and Screen. Both classes must provide an implementation for the print method as required by the Printable interface.


In the InterfaceExample class, we create objects of the Printer and Screen classes that implement the Printable interface.


We call the print method on each object, and the appropriate implementation is executed depending on the class of the object.



Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.