Salesforce APEX Class Vs Interface

Varun   Varun 472 Views
Class is a template or blueprint from which objects are created. An object is an
instance of a class. All objects have state and behavior, that is, things that an object knows about itself, and things that an object can do.

Class contains member variables ( attributes ) and methods and methods are used to control behavior.

E.g. Salesforce standard, Opportunity is your class which has fields as member variables and actions like "Save","Clone" as your methods. or other simple example is, Man as class  ( height, weight like your variables and walk(), talk() etc. as your methods ( actions )).

public class Man{
  public Double height;
  public Double weight;
 public  void walk(){
 // code implemented
}
 public  void talk(){
 // code implemented
}
}


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.

public class Human{

 public Interface HumanInterface{ 
 public Double height;
 public Double weight;
 public  void walk();
 public  void talk();
}

}

Interface is designed to set protocol for class implementation. when class implements interface then it is mandatory for class to define/add code for all actions.

Note:
i) you can not reduce methods visibility while implementing interface. 
ii) single class can implement multiple interfaces.

public class Human{

 public Interface HumanInterface{ 

 public Double height;
 public Double weight;
 public  void walk();
 public  void talk();

}

public class Man  implements  HumanInterface {
  public Double height;
  public Double weight;
 public  void walk(){
 // code implemented
}
 public  void talk(){
 // code implemented
}
}

}