Class and Object in Apex

Class: A class can be defined as a blueprint or template that describes the behavior/states of the object.

Objects: Objects have states and behaviors. An object is an instance of a class.

Example: A student has states – e.g., name, roll-no. 

What goes into class?

  • The class represents the blueprint of the object.
  • The class comes within curly braces.
  • The class has one or more methods.
  • The methods should be declared inside a class.
Salesforce Class and Object in Apex
Salesforce Class and Object in Apex
Salesforce Class and Object in Apex

How to create the Object of the class?

Below is the syntax to create the object of the class:

Car a = new Car();

Car a-> Declaration

new Car-> Instantiation

a-> car speed=70

“a” is the reference that holds the memory address of the Car object

Example:

Output:

Salesforce Class and Object in Apex

Example:

Output

Salesforce Class and Object in Apex

Access Modifiers

Apex grants us to use the private, protected, public, and global access modifiers while defining methods and variables.

Interface methods have no access modifiers. These methods are always global.

By default, a variable or method is visible mainly to the Apex code inside the defining class. We must specify the method or variable as public to make it available to other classes in the same application namespace.

The following access modifiers are available:

  • Public: Any Apex can use the method or variable in this namespace or application.
  • Private: This is the default modifier that means the method or variable is available only inside the Apex class in which it is defined.

If we do not specify an access modifier, then the variable or method will be private.

  • Protected: The method or variable is visible to any inner class in the defined Apex class.

We can use this access modifier, for instance, methods and member variables.

  • Global

The method or variable can be used by any Apex code that can access the class.

Example:

Output:

Salesforce Class and Object in Apex

Example:

Output:

Salesforce Class and Object in Apex

Example:

Output:

Salesforce Class and Object in Apex

Pin It on Pinterest

Share This