3.2 Use methods

The concept

Following our previous post , a dog not only has some attributes like name and gender, it can also do some certain behaviours. Like, they can bark, walk, they can greet you. When implemented in programming, such behaviours are defined as methods or functions. Method and function in apex can be used interchangeably. Here is the code, following our previous post:

public class Dog
{
    //Last post's code here
    //...
    public void bark()
    {
        System.debug('Woof, Woof!');
    }
    
    public void greeting()
    {
        System.debug('Hello, my name is ' + name);
    }
    
    public String retrieveDogInfo()
    {
        return 'Name: ' + name + '; Gender: ' + gender;
    }
}

To reopen our existing class, in developer console, click File > Open > classes, Find dog and open the file. You can append today’s code into our dog class.

Now let’s try using the class in our anonymous block!

Dog d = new Dog();
d.age = 20;
d.name = 'Happy';
d.gender = 'male';
d.breed = 'Golden Retriever';
d.isPuppy = false;

d.bark();
d.greeting();
String dogInfo = d.retrieveDogInfo();
System.debug(dogInfo);

You result in debugger log should look similar to this:

classmethod

A bit explanation

I guess you can read through the code and guess the meaning of it. But it does need some explanation to understand how it works.

When we look at this code:

    public void bark()
    {
        System.debug('Woof, Woof!');
    }

public is the access modifier. It is pretty much the same as used for class variables.

void is the return type of the function. void means we don’t need to return anything for this method. We can return any type from a method. As in retrieveDogInfo() method, we returned a String in that case. We can use that value or assign it to a variable.

bark is the method name. Just like variable names, we can almost name it to be anything you want. However, make sure you want to make it meaningful.

The () after bark tells the compiler it is a function. Inside (), we can define a number of parameters. We will be talking more about parameters in our next post.

Everything inside the {} is function body.

You can access class variables within the method.

Exercise

In your Person class defined in 3.1’s exercise, define some methods to greet and return this Person’s information.

Next Post

3.3 Use methods that takes parameters

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 *