Tuesday, May 11, 2010

Interfaces for Apex Class - Salesforce

Implementing Interfaces for Apex Classes

An interface is like a class in which none of the methods have been implemented, the method signatures are there, but the body of each method is empty. To use an interface, another class must implement it by providing a body for all of the methods contained in the interface.

public class InterfaceClass
{
    //Lets consider a Bank trnasaction interface which indeed used by 3 banks BankA, BankB and BankC
    public Interface bankTransactionInterface
    {
        double deposit();
        double withdrawal();
   }
    
    //We have to implement the two methods declared in the interface for BankA
    public class BankA implements bankTransactionInterface
    {
        public double deposit()
        {
            //process the deposit
            double depositedAmount = 250;
            return depositedAmount ;
        }
        
        public double withdrawal()
        {
            //process the withdrawal
            double withdrawalAmount = 350;
            return withdrawalAmount ;
        }
       
    }
    
    //We will take another class for BankB and declare it as virtual as it is parent of BankC which has different deposit porcess but same withdrawal process as BankB.
    //For this we have to declare the deposit method as virtual and use override keyword when overriding it for BankC like showed below
    public virtual class BankB implements bankTransactionInterface
    {
        public virtual double deposit()
        {
            //process the deposit
            double depositedAmount = 450;
            return depositedAmount ;
        }
        
        public double withdrawal()
        {
            //process the withdrawal
            double withdrawalAmount = 1000;
            return withdrawalAmount ;
        }
    }
    
    public class BankC extends BankB 
    {
        public override double deposit()
        {
            //process the deposit
            double depositedAmount = 750;
            return depositedAmount ;
        }
    }
} 
'Hope this is helpful 

4 comments:

  1. yeh it is helpful as it has been explained in very simple way

    ReplyDelete
  2. how to execute in page

    ReplyDelete
  3. can u tell me test method also

    ReplyDelete
  4. you can use Development console to run the program.

    ReplyDelete