What is an Interface in Apex

Interface in Apex is a collection of unimplemented methods and it contains the method signature, but the body of each method is empty. To use Interface in Apex, another Apex class must implement it by providing the body for all the methods contained in Apex interfaces. Interface in Apex are given as global.


Public interface Exam {
    Account Show(Sting S);

All the methods in the interface are public and abstract methods. Interface also contains, Final Static Data members. The Class which is implemented this interface should define all the methods in the interface.

  • Interfaces can provide a layer of abstraction for our code.
  • Defining an Interface in Apex is similar to defining a new class in Apex.


interface test {
	public String Show()
	void disp();
	global Class Example implements test {
		return 'Prasaanth';
	public void disp( ) {
		Account a = new Account(Name='Prasanth');

We should define method in the interface, if not it will display an error. For interface in Apex, we can not create an object.

Class Test { }

Test t = new Test( );

interface Demo {
  void Show ( );
  • Demo d = new Demo ( ); is not allowed because interface in Apex contains only unimplemented methods and static methods.
  • Demo d = e; is allowed because ‘e’ is the object of the class which is implementing the demo interface.
  • Demo d = t; is not allowed because test class in not implemented interface demo.

Interface Iterator.

This is the interface defined by Salesforce in Apex. Interface Iterator has 2 methods .

Boolean hasNext( )

Boolean hasNext( ) method return true if there is another item in the collection being traverse else returns ‘false’

AnyType next()

AnyType next() method returns the next item in the collection. Both methods given above should be declared as a global or public

How to create Custom Iterator in Apex.

public class Prasanth implements Iterator <Account> {
	public List <Account> acc;
	public Integer i;
	public Prasanth( ) {
		acc = [SELECT name FROM Account];
		i = 0;
	public boolean hasNext () {
		return false;
		return true;
	Public Account next() {
		return null;
		return a[i-1];

Interface iterable

Iterable is interface in which we have a method Iteratorclass Iterator()


class Bened implements Iterable<Account> {
	public Iterator<Account> iterator() {
		Prasanth P = new Prasanth();
		Iterator<Account> it = s;
		return it;


public class SampleIterator {
	public List <Account> acc;
	public List <Account> getAcc() {
		return acc;
	public SampleIterator() {
		acc = new List <Account>();
	public pageReference Show() {
		Iterable <Account> my = new tkartiterable();
		Iterator <Account> test = my.Iterator();
		while(test.next()!-null) {
			Account a = test.next();

Visualforce page

<apex:page controller="SampleIterator">
       <apex:commandButton value="click" action="{!show}"/>
          <apex:pageBlockTable value="{!acc}" var="a">
          <apex:column value="{!a}"/>