How To Create An Apex Class

by | Aug 8, 2022 | Salesforce

Home » Salesforce » How To Create An Apex Class

Introduction

Apex is a strongly typed language based on the OOPs concept means it has classes and objects. Class is a blueprint or a boundary from which an object is created, and an object is an instance of a class. Apex and Java classes are similar to each other. A class consists of variables/data members, methods, and constructors (a special type of method).

Components of an Apex Class

It has the following components:

Attributes: Attributes are data members that define the object state. It holds the value respective to the data type for each variable.

Methods: A method is a block of code that has multiple instructions and allows objects to perform an action.

Constructors: Constructors are special methods that are called implicitly when an instance of a class is created.

By default, methods and variables are private in Apex. If we want to make them public, we need to add public access modifier explicitly.

Steps to create an Apex Class

  1. Go to the Developer Console by clicking the gear icon present in the top right position.
  2. Click on file, then new, and then choose Apex class.

Then you will be presented with the below syntax.

public class ClassName{
//code
}

 

Class is a ‘keyword’, and public is an access modifier

Example

public class ClassExample
{
public static void insertDoctors()
{
List<Doctor__c> dc = new List<Doctor__c>
{
new Doctor__c(name='Akriti', doctor_email__c='akriti@gmail.com', monthly_salary__c=90000),
new Doctor__c(name='Akriti1', doctor_email__c='akriti1@gmail.com', monthly_salary__c=190000),
new Doctor__c(name='Akriti2', doctor_email__c='akriti2@gmail.com', monthly_salary__c=290000),
new Doctor__c(name='Akriti3', doctor_email__c='akriti3@gmail.com', monthly_salary__c=390000),
new Doctor__c(name='Akriti4', doctor_email__c='akriti4@gmail.com', monthly_salary__c=490000)
};
insert dc;
}
public static void deleteDoctors()
{
List<Doctor__c> dc = [Select Name FROM Doctor__c WHERE Name
LIKE 'Akriti%'];
delete dc;
}
public static void undeleteDoctors()
{
List<Doctor__c> dc = [Select Name FROM Doctor__c WHERE Name
LIKE 'Akriti%' all rows];
undelete dc;
}
public static void updateDoctors()
{
List<Doctor__c> dc = [Select Id FROM Doctor__c WHERE
Monthly_Salary__c > 100000];
for(Doctor__c k: dc)
{
k.choose_state__c = 'Himachal Pradesh';
k.choose_city__c = 'Shimla';
}
update dc;
}
}

 

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