How To Use Objects In Apex

by | Aug 9, 2022 | Salesforce

Home » Salesforce » How To Use Objects In Apex

Introduction

An object is an instance of a class. It denotes an entity in the real world. Object creation in Apex is similar to object creation in Java or other OOPs language.

How to use objects in Apex

We create objects to access the variables or methods functionality present in the class. Actions or logic in the methods of the class will be executed when an instance of that class is created and calling the methods using the object reference variable.

Example

public class CalculatorClass {
public Integer add(Integer num1, Integer num2){
return num1 + num2;
}
public Integer sub(Integer num1, Integer num2){
return num1 - num2;
}
public Integer mul(Integer num1, Integer num2){
return num1 * num2;
}
}
Open Anonymous Window and Write the below code.
CalculatorClass cc = new CalculatorClass();
system.debug(cc.add(2,6));
system.debug(cc.sub(3,2));
system.debug(cc.mul(2,9));

 

Explanation

Here, we have created a class, ‘CalculatorClass’ in which parametrized methods such as add(), sub(), and mul() are present. Now, to execute our code or to perform the actions by calling apex methods, we have created an object(an instance of a class) with the help of a new keyword. ‘new’ keyword allocates the memory for the variables or methods which are declared in a class.

CalculatorClass cc = new CalculatorClass(); //object creation

Now we are calling methods present in our class using object reference variable cc and printing them to see the output using System.debug() where debug() is a static method of an inbuilt System class.

System.debug(cc.add(2,6)); // this will call add() with num1 as 2 and num2 as 6

System.debug(cc.sub(3,2)); // this will call sub() with num1 as 3 and num2 as 2

System.debug(cc.mul(2,9)); // this will call mul() with num1 as 2 and num2 as 9

 

Author

0 Comments

Submit a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author