Salesforce Menu

Classes and Object in Apex

In this page, we will learn about Apex classes and objects. In object-oriented programming, we design a program using classes and objects.

What is a class in Apex

Class is a concept or prototype or template i.e. it is a logical entity. A class is having member method and member data.

Technically, a class is a group of objects which have common properties all together.


Syntax to declare a class:

class  {  

What is an object in Apex

Any real world entity that has state/data and behavior/method is known as an object. For example: marker, book, table, chair, mouse, car etc.

Technically, we can say object is an instance of a class or in other words you can say it is an implementation of a class.

For Example, Marker is an object. Its name is Luxor; color is white, known as its state/data. It is used to write, so writing is its behavior/method.

An object is an instance of a class, which means an object is a real time implementation of a class.

Syntax to define an object:

Class_name refVariable = new Class_name();

New keyword in Apex

The new keyword is used to allocate memory at runtime. All objects always get memory in heap memory area.

Class and Object Example:

In this example, we have created a Employee class which has two data members id and name. We are creating the object of the Employee class by new keyword and printing the object’s value.

//Apex Program to illustrate how to define a class, fields and methods
//Defining a Employee class.  
public class Employee {  
 //defining fields  
 integer empId;//field or data member or instance variable  
 String empName;  
 //creating method inside the Employee class  
 public void getEmpDetails(){  
   empId = 101; // setting the value of instance variable
   empName = 'Sanjay'; // setting the value of instance variable  
  //Printing values 
  System.debug('empId = ' + empId);//accessing member variable  
  System.debug('empName = ' + empName);  

How to create an Object of this class:

Employee emp = new Employee();


empId = 101
empName = Sanjay

Memory Representation of Employee Program as below:

Above Program’s memory representation explanation:

Using new keyword, it will allocate a memory of type Employee where instance data members got initialized into memory that is referred by emp and then using emp we are referring the instance members.

Subscribe Now