Apex class, variables, constructor, and methods in Salesforce. (2023)

If you're familiar with Java or dotnet applications, you might find that everything is written as a class. There are different levels of access. You can also define the class inside a class as inner class and outer class etc.

Salesforce also provides Java-like syntax. The syntax can be to define a class or variables in a class or a wrapper class, everything is similar to the syntax followed in Java programming.

Let's look at a class and what you can do in a class in Salesforce.

public class A_Class_Name{ // Variablespublic static string a_Variable {get;set;} // Constructorpublic A_Class_Name(){ // Konstruktor Geschäftslogikcode } // Método public void a_Method_Name(Integer a_Variable1, Ingeter a_Variable2){ // Geschäftslogikcode } }

Here's what we can do in class.

  1. class definition
  2. variable declaration
  3. class constructor
  4. Definition of teaching methods.

All of the above syntaxes have one thing in common: access modifiers. Access modifiers can be public, private, protected, and global.

Learn more about access modifiers.

class definition


(Video) what is apex class,constructor and method in salesforce | Salesforce Devlopment Tutorial in hindi

Access_Modifier class A_Class_Name{ // Uma classe chamada "A_Class_Name"}

A class definition consists of 3 parts, namely access modifiers, class keyword and class name. This is also how it is defined in Java. But here in Salesforce there is one more keyword that can be defined and that is"communicate"j"no sharing"🇧🇷 If the user doesn't set anything, it won't be shared by default.


/* * Access modifier: public * Class name: A_classname_A * Description: This is an example class to demonstrate with shared access * Author: author_name. */public shared class A_Class_Name_A{ // This is class shared (user mode) // A public class shared access // and name "A_Class_Name_A"}/* * Access modifier: public * class name class: A_Class_Name_B * Description: This is a sample class intended to be demonstrated without share access. * Author: author_name. */public non-shared class A_Class_Name_B{// This is a non-shared class (system mode) // A public class with non-shared access // and name "A_Class_Name_B"} /* * Access modifier: public * Name class : A_Class_Name_C * Description : This is an example class intended to be demonstrated without share access * author: author_name. */public class A_Class_Name_C{ // This is not a shared class (system mode) // By default, the class is not shared. // A public class that does not share // and is named "A_Class_Name_C" }

To use:

  • existgovernor limitsin Salesforce also for Apex code.
  • Number of characters for a class in 1 million.
  • The maximum amount of code used by all Apex code in an organization is 6 MB.

Learn more about system mode and user mode.

variable declaration

Variable declaration in Salesforce is similar to Java. You can declare null variables and variables with some values. All variables have one data type or another, for example sObject, Primitive or Enum.


Access_Modifier Data_Type a_Variable_Name;

The access modifier is optional because variables can be declared locally or inside the class and can also be used by reference outside the class.

(Video) APEX Programming -APEX Class,Constructors

Date_Type can be a primitive data type, an object, or an enumeration.

a_variable_name can be any variable name required by business logic.


// a variable of type Stringpublic string a_New_String; // a variable of type Integerprivate integer a_New_Integer;

To use:

  • A variable can also be static.
  • Variables can be declared within scope and used locally.
  • The variable name must be unique within the scope.
  • The system initializes an uninitialized boolean variable to false.
  • Multiple variables can be declared and initialized separately in a single declaration using commas.
    • Ej: Entero a,b,c;
  • If you declare a variable and don't initialize it with a value, it will be null.
  • null means the absence of a value.
  • You can also assign null to any variable declared with a primitive type.
  • All data types, objects and classes have some system-defined default methods.
    • Bsp.: valueOf(), size(), Length().
  • Apex is also case insensitive. This means that the integer A and the integer a are equal. And it will throw errors.
  • You can define a constant variable with the 'final' keyword.

class constructor

The constructor is the first method executed when a class object is created. The constructor can be with or without an attribute. You don't have to write builder code if you don't need to. The system creates a default constructor with no attributes (default is no constructor arguments).

  • The constructor name is always the same as the class name.
  • The constructor has no return type.


Access_Modifier class A_Class_Name{ // Ein Konstruktor.Access_Modifier A_Class_Name(){// Código do construtor.}}

The constructor can be with or without an argument, as shown below. The examples below are also referred to asconstructor overload.

(Video) Apex Class variables - Salesforce Development - Apex Development


/* * access modifier: public * class name: A_Class_Name * description: This is an example class to demonstrate how the constructor can be defined. * Author: author_name. */public class A_Class_Name{ /* * Access modifier: public * Description: This is a no-argument constructor. * Arguments: None. * Author: author_name. */public A_Class_Name(){ // No argument (No constructor argument)// Constructor code.} /* * Access modifier: public * Description: This is a constructor with arguments. * Arguments: 1 ******** 1) a_variable - string type - <reason> * author: author_name. */ public A_Class_Name(String a_Variable){ // Builder code. // The "a_Variable" argument can be of any data type. // In this example, it is of type String.} /* * Access modifier: public * Description: This is a constructor with one argument. * Arguments: 2 ******** 1) a_Variable - String Type - <Reason> ******** 2) a_Flag - Boolean Type - <Reason> * Author: author_name. */ public A_Class_Name(String a_Variable, Boolean a_Flag){ // Constructor code. // Argument "a_Variable" and "a_Flag" can be of any data type. // In this example it is of type String and Boolean. 🇧🇷

To use:

  • If you write a constructor with one argument, you can use the constructor to create an object with those arguments.
  • If you create a constructor that accepts arguments and still want to use a no-argument constructor, you must create your own no-argument constructor in your code.
  • Once you create a constructor for a class, you no longer have access to the default public constructor with no arguments.
  • you can createbuilder overloaded, which means more than one constructor with different parameters.
  • If a controller is referenced in the Visualforce page, no argument constructors of that class are executed when a page is loaded.
  • The constructor has no return types.
  • @future annotation methods cannot be called from the constructor.

A new object of the above class type can be created as follows.

/* * An object "a_New_Object1" is created and * no argument constructor is executed. */A_Class_Name a_New_Object1 = new A_Class_Name();/* * An object "a_New_Object2" is created and * a constructor is executed, taking the parameter as a string. * "a_Variable" contains 'Test String Value' */A_Class_Name a_New_Object2 = new A_Class_Name('Test String Value');/* * An object "a_New_Object3" is created and * a constructor is executed that receives the parameter as string and boolean . * "a_Variable" contains "Test String Value" * "a_Flag" contains "True" as a boolean value. */A_Class_Name a_New_Object3 = new A_Class_Name('Test String Value', True);

Definition of the method in the classroom.

If you want to run business logic, you can define a method in a class and call that method when needed.


Access_Modifier Return_Type_Method_Name(Date_Type_Attribute1, Date_Type_Attribute2, ...){ // Methodencode.// Geschäftslogik.}

A method definition consists of several parts, an access modifier, a return type, followed by the name of the method. Setting the attribute is optional.

The access modifier can be public, private, protected, and global. The default access modifier is private.

(Video) Salesforce development - Apex Constructors

All methods have a return type, which can be any primitive data type or sObject.

You can specify a method name, which provides the appropriate name for the logic written in the method.

Attributes are optional. By defining attributes, you can pass the input value to the method needed to execute the business logic. If business logic requires some input values, set the attribute. If your business logic doesn't require input, you don't need to set an attribute and leave it blank.


/* * Methodenname: m_Add * Zugriffsmodifikator: public * Rückgabetyp: Integer * Attribute: 2 ******* 1) a_Value1 - Integer-Typ ******* 2) a_Value2 - Integer-Typ */public Integer m_Add(Integer a_Value1, Integer a_Value2){integer a_Result;a_Result = a_Value1 + a_Value2;return a_Result;}

After writing the method, you can call it as shown in the following example. Let's assume that the name of the class in which this method is written is A_Calculator.

// Create an object of type A_Calculator a_Object = new A_Calculator();//Call the method name as Object.MethodName();Integer a_Result = a_Object.m_Add(5,4);// Check the value with assert statement . System.assertEquals(9,9);

To use:

  • A method with void as a return type does not need to write a return statement at the end of the method.
  • A method that returns a return type value must be written at the end of the method's return statement to return the same data type value. Example: The return type is string, so a string variable must be returned at the end of the method.
  • Methods can be static.
  • heugovernadoresgrenzealso when writing a method.
  • The size limit of the method is 65,535 bytecode of instructions in compiled form.


Salesforce: Using Builders

(Video) Apex Tutorial || Salesforce Development || Apex Constructor with example and Constructor types

Salesforce: Systemklasse


How many methods are there in Apex class? ›

There are two modifiers for Class Methods in Apex – Public or Protected. Return type is mandatory for method and if method is not returning anything then you must mention void as the return type. Additionally, Body is also required for method.

What is the difference between constructor and method in Apex? ›

The syntax for a constructor is similar to a method, but it differs from a method definition in that it never has an explicit return type and it is not inherited by the object created from it.

What is best practice for Apex coding? ›

Other best practices for Apex include:
  • Bulkify your data manipulation language (DML) statements and use the built-in Limits methods. ...
  • Write comments with a good balance between quality and quantity (explain, but don't over-explain). ...
  • Avoid nesting loops within loops.
  • Avoid SOQL queries and DML statements inside loops.

Can we call method from constructor in Apex? ›

Yes, you can call the parent class's constructor using super() .

What are the 4 classes in Apex? ›

Available Legends
  • Offensive.
  • Defensive.
  • Recon.
  • Support.

What are the 4 types of constructor? ›

Constructor Types
  • Default Constructor.
  • Parameterized Constructor.
  • Copy Constructor.
  • Static Constructor.
  • Private Constructor.
Jul 1, 2022

What are the 3 types of constructor? ›

There are mainly 3 types of constructors in C++, Default, Parameterized and Copy constructors.

What are the 4 differences between method and constructor? ›

A method can be invoked only on existing object. A constructor must have same name as that of the class. A method name can not be same as class name. A constructor cannot be inherited by a subclass.

How many days it will take to learn Apex? ›

4 weeks for you to learn Salesforce Apex.

How can I pass Apex fast? ›

Tips for Success
  1. Complete the APEX orientation course (see below).
  2. Familiarize yourself with the APEX expectations and procedures.
  3. Commit to Learning.
  4. Set specific goals based on your desired outcomes.
  5. Be conscientious about completing assignments.
  6. Plan regular meetings with you Teacher or Coach.

Is Apex coding easy? ›

Learning Apex will not be easy but you can do it. Persevere! It is a journey that will make you smarter and more desirable on the job market.

Which constructor will call first? ›

This is why the constructor of base class is called first to initialize all the inherited members.

Can constructor return a value in Apex? ›

Constructors return an instance of a class, so they can't have any other return values.

How many types of constructor are there in Apex? ›

Types of Constructor in Apex programming.

Default Constructor. Non-parameterized Constructor. Parameterized Constructor.

Which legend is best in Apex? ›

Combined with her Passive and Ultimate, Wraith is perhaps the best Apex Legends character for initiating and escaping team fights. With that said, Wraith is also one of the more challenging legends to master.

What are the three roles in Apex? ›

The main roles in Apex are: scout, fragger, support, and in-game leader (IGL).

Does Apex have 4 squads? ›

Our loot distribution is designed for three people per squad. Even something like the banners placed around the map don't have room for a fourth.

How many zones are there in Apex? ›

There are eleven maps in Apex Legends.

How many divisions are in Apex? ›

Ranks. Ranked Leagues features six competitive tiers: Bronze, Silver, Gold, Platinum, Diamond, and Apex Predator. All of the tiers except Apex Predator have four divisions; Gold IV, Gold III, Gold II, and Gold I, for example, with Gold I being the top division in Gold tier.

How many countries are there in Apex? ›

Asia-Pacific Economic Cooperation (APEC) is a forum of 21 Asia-Pacific economies. APEC's member economies are home to more than 2.9 billion people and make up over 60 per cent of global GDP. APEC partners make up around 75 per cent of Australia's total trade in goods and services.

What are the 2 types of constructors? ›

There are two types of constructors parameterized constructors and no-arg constructors.

Why is it called a constructor? ›

Constructors in C++

Constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object which is why it is known as constructors.

How many constructors can a class have? ›

You can have 65535 constructors in a class(According to Oracle docs). But IMPORTANTLY keep this in your mind.

How many types of constructors are there in Salesforce? ›

There are 3 types of constructors: 1.

What is called constructor? ›

What Does Constructor Mean? A constructor is a special method of a class or structure in object-oriented programming that initializes a newly created object of that type. Whenever an object is created, the constructor is called automatically.

Why are constructors used? ›

Constructor in java is used to create the instance of the class. Constructors are almost similar to methods except for two things - its name is the same as the class name and it has no return type. Sometimes constructors are also referred to as special methods to initialize an object.

What are the two types of methods? ›

There are two main categories of research methods: qualitative research methods and quantitative research methods.

What are the 5 types of constructor implementation? ›

In C#, constructors can be divided into 5 types
  • Default Constructor.
  • Parameterized Constructor.
  • Copy Constructor.
  • Static Constructor.
  • Private Constructor.
Sep 15, 2022

Can we overload main method? ›

Yes, We can overload the main method in java but JVM only calls the original main method, it will never call our overloaded main method.

What are the methods of list in Apex? ›

List Methods
  • add(listElement) Adds an element to the end of the list.
  • add(index, listElement) Inserts an element into the list at the specified index position.
  • addAll(fromList) ...
  • addAll(fromSet) ...
  • clear() ...
  • clone() ...
  • contains(listElement) ...
  • deepClone(preserveId, preserveReadonlyTimestamps, preserveAutonumber)

What is methods in Apex? ›

In Apex, all primitive data type arguments, such as Integer or String, are passed into methods by value. This fact means that any changes to the arguments exist only within the scope of the method. When the method returns, the changes to the arguments are lost.

How many Apex classes are there in Salesforce? ›

Options include String, Integer, Boolean, sObject, and more. You can find all the Apex variables data types on the Salesforce website.

How many Invocable methods are in Apex class? ›

Only one method in a class can have the InvocableMethod annotation.


1. Apex Class Variables
2. Salesforce Apex 28 | Interface | Constructor, Initialization, Passing Variables | Type of
(Swapna Salesforce )
3. Salesforce Apex Master Class (Ep. 13) - What is a Constructor in Apex?
(Coding With The Force)
4. 6. Difference between Method & Constructor
(Salesforce Casts)
5. Salesforce Apex Tutorial for beginners: What is Private Modifiers and Constructor in Salesforce
6. 4.How to Apex Method, constructor, Object creation and use of this keyword
Top Articles
Latest Posts
Article information

Author: Madonna Wisozk

Last Updated: 05/05/2023

Views: 6637

Rating: 4.8 / 5 (48 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Madonna Wisozk

Birthday: 2001-02-23

Address: 656 Gerhold Summit, Sidneyberg, FL 78179-2512

Phone: +6742282696652

Job: Customer Banking Liaison

Hobby: Flower arranging, Yo-yoing, Tai chi, Rowing, Macrame, Urban exploration, Knife making

Introduction: My name is Madonna Wisozk, I am a attractive, healthy, thoughtful, faithful, open, vivacious, zany person who loves writing and wants to share my knowledge and understanding with you.