3.7 Using static modifier

The concept

In the previous posts, we have learnt how to create a class and variables and functions within. But there are times, that a variable or function should belong to the whole class type, not just one object instance. For example, we might be interested on how many dogs we have made in our current environment. That count of all the dogs should be belonged to the dog class, not just one dog. We can utilise static modifier in this case.

Let’s reopen our dog class:


public class Dog
{
    public Integer age;
    private String name;
    private String gender;
    public String breed;
    public Boolean isPuppy;
    public static Integer dogCount = 0;
    
    public Dog(String name) 
    {
        this.name = name;
        dogCount++;
    }
    
    public static void dogReport()
    {
        System.debug('There are currently ' + dogCount + ' dogs created');
    }
    //...
}

And in our anonymous block:


Dog d = new Dog('Happy');
Dog anotherDog = new Dog('Crazy');
System.debug(Dog.dogCount);
Dog.dogReport();

A bit explanation

When a method or a class is modified as static. It means this variable or function belongs to the whole class, not just one object instance. In the above code, it doesn’t belong to d or anotherDog. So if we want to use static variable or function, just use [ClassName].[variableName] or [ClassName].[functionName]. No need to use a specific object here.

A static variable can be used and modifier within a normal class function. But a static function cannot call a normal class function or use a normal class variable.

Exercise

Use a static variable to calculate the total price of all the commodities we created using Commodity class. And create a static function to output the total price.

Next Post

3.8 Function overloading

Subscribe to Sfdcinpractice

Subscribe to get the latest blogs and tutorials of sfdcinpractice. No spam, no trash, only the awesome posts from sfdcinpractice. 

Leave a Reply

Your email address will not be published / Required fields are marked *