Constants are variables which do not change their value once declared or assigned a value. We use them when we want a variable to only have one value throughout the program execution.

In Apex, constants are declared with the keyword ‘final’.

The following code block has the constant variable ‘regularCustomerDiscount’.

public class CustomerOperationClass {
   static final Double regularCustomerDiscount = 0.1;
   static Double finalPrice = 0;
   public static Double provideDiscount (Integer price) {
      //calculate the discount
      finalPrice = price - price * regularCustomerDiscount;
      return finalPrice;

This is a class which has two variables (one of which is constant). And a method which takes one variable (price) to calculate the final price. The static keyword makes the variables accessible even if you never create an instance of the class(?).

It would be called with the following in the  anonymous window:

Double finalPrice = CustomerOperationClass.provideDiscount(100);
System.debug('finalPrice '+finalPrice);

– What exactly does static mean?
– If static is about making the variables or methods accessible, isn’t that already done by the public access modifier?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s