Objects And Classes In Salesforce

Introduction

Apex is an Object-Oriented Programming Language that is used for building logic or applications on the Force.com platform, containing classes and objects.

We can solve real-world problems easily with this approach. It works on the principles of Inheritance, Abstraction, Polymorphism, and Encapsulation.

Classes in Salesforce

Class is a boundary in which we write our variables and methods to perform business logic. It’s not a physical but a logical entity and a group of similar entities.

public class ClassName{
//variables
//methods
}

 

Objects in Salesforce

An object is an instance of a class, and we can have multiple instances of a particular Apex class. We can invoke variables or methods with the help of object reference variables. In other words, we make use of Objects to call the functionalities from the class.

Objects get the memory by a new keyword in the heap by instantiating it.

Contact con = new Contact(); //Initialization of Object

Calling a Class using Object in Salesforce

In the example below, we have a class called Fitness, and this class contains two parametrized methods which are calculateBMI() and calculatePace() containing the logic to calculate BMI and Pace.

Now we have created an instance of a class to access the methods present in the class.

//object creation using the new keyword
Fitness fit = new Fitness();
//accessing method calculateBMI using reference variable fit and printing it.
System.debug('BMI for height and weight is: ' + fit.calculateBMI(65, 1.2));

 

Example

public class Fitness
{
public Decimal calculateBMI(Decimal bodyWeight, Decimal bodyHeight)
{
if(bodyWeight < 0 || bodyHeight <= 0)
{
return -1;
}
Decimal bmiValue = (bodyWeight)/(bodyHeight * bodyHeight);
return bmiValue;
}
public Decimal calculatePace(Decimal distance, Decimal timeTaken)
{
if(distance < 0 || timeTaken < 0)
{
return -1;
}
Decimal paceValue = (distance)/(timeTaken/60);
return paceValue;
}
}


//object initilization
Fitness fit = new Fitness();
System.debug('BMI for height and weight is: ' + fit.calculateBMI(65, 1.2));
System.debug('BMI for height and weight is: ' + fit.calculateBMI(75, 1.3));
System.debug('Pace (km/hr) for km in minutes is: ' + fit.calculatePace(12.5, 80));

 

Leave a comment

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