Thursday, October 2, 2014

How to understand and use Interface, Abstract and Virtual definition modifier in apex Salesforce

Ok so this is a very conceptual module in apex or OOPs programming.

Interface is a which none of the methods have been implemented but when its implemented then it is mandatory to define all of its declared method in the implementing class. Also we cannot define any fields in interface and all the method are final and pubic.

Example:

public interface custom_Interface{
    void CallFirst();
    Void CallSecond();
}
public class Implement_custom_Interface implements custom_Interface{
    public void CallFirst(){
        //
        system.debug('***First**');
    }
    public void CallSecond(){
        //
        system.debug('***Second**');
    }
}

Abstract class is class with only declaration and no definition but its mandatory to override all the method.

Example:

public abstract class custom_Abstract{
    public abstract string AbstractFirst();
    public abstract string AbstractSecond();
    public void noReturn(){
    }
}
public class Implement_custom_Abstract extends custom_Abstract{
    public override string AbstractFirst(){
        system.debug('***From Abstract Extends Class***');
        return null;
    }
    public override string AbstractSecond(){
        system.debug('***From Abstract Extends Class***');
        return null;
    }
}

Virtual class is having definition of the method and if you need you can override the method, but its not mandatory to implement all the methods.

Example:


public virtual class coustom_Virtual{
    public virtual void OverFirst(){
        system.debug('****From  Defination****');
    }
    public virtual void OverSecond(){
        system.debug('****From  Defination****');
    }
}
public class Implement_coustom_Virtual extends coustom_Virtual{
    public override void OverFirst(){
        system.debug('!!!From  Declairation!!!');
    }
}
Hope this helps you!!

No comments:

Post a Comment