Wednesday, January 22, 2014

What is property in Apex? Explain with advantages

What is property in Apex? Explain with advantages

Apex mainly consist of the syntax from the well known programming language Java. As a practice of encapsulation in java we declare any variable as private and then creates the setters and getters for that variable.
private String name;
public void setName(String n)
{
  name = n;
}
public String getName()
{
 return name;
}

However, the Apex introduced the new concept of property from language C# as shown below:
public String name {get; set;}

As we can see how simple the code is and instead of using nearly 8 to 11 lines all done in 1 line only. It will be very useful when lots of member is declared in Apex class. It has another advantage in “number of lines of code” limit by salesforce which will drastically reduced.

Ex:
public class BasicProperty {
   public integer prop {
      get { return prop; }
      set { prop = value; }
   }
}
BasicProperty bp = new BasicProperty();
bp.prop = 5;                   // Calls set accessor
System.assert(bp.prop == 5);   // Calls get accessor


No comments:

Post a Comment