How to Create and Use Apex Classes, Methods and Constructors

May 08, 2025
595 Views
How to Create and Use Apex Classes, Methods and Constructors

Welcome to day 7 of the 10 day Apex series. In the previous article we have seen how to work with DML Operations and Exception Handling in apex. Now In this blog we will talk about Create and Use Apex Classes, Methods and Constructors.

Apex is a strongly typed, object-oriented programming language that enables us to create customization and automate business processes on the Salesforce platform. This blog explains the main elements of Apex like classes, methods and constructors. It will also cover the various access modifiers such as public, private and global. Read on to learn how to develop and structure Apex code in a clean and efficient manner for business needs.

Introduction to Apex Classes

In Apex, a class is a main task for creating objects and maintaining code into logical components. Classes are used to group required variables (properties) and methods (functions) altogether, which will make managing and reusing code much easier and better.

Creating a Basic Apex Class

The easiest way of an Apex class can be defined with minimal syntax. Below is an example of a basic class that shows a simple utility:

public class Utility {
    // A simple class with no properties or methods
}

The class is declared with the keyword class preceded by an access modifier (public).

Methods in Apex

Methods in Apex let the class perform required or needed actions. A method consists of a name, a return type and parameters (only if required). Methods will perform operations, return values or modify class attributes.

Creating a Simple Method

Below is an example of a method that displays a greeting message:

public class Utility {
    // A method that returns a greeting message
    public static String getGreeting() {
        return 'Hello, Salesforce!';
    }
}

In the above example, the method getGreeting() is marked aspublic and static. Declaring a method as static will let us know that it will be called on the class rather than demanding an instance of the class.

Methods with Parameters

Methods may need an input to perform operations. Below is a basic example of a method that will take a name as a parameter and returns a customized greeting:

public class Utility {
    // A method that takes a name and returns a personalized greeting
    public static String getPersonalizedGreeting(String name) {
        return 'Hello, ' + name + '!';
    }
}

Above piece demonstrates how parameters are declared with a type String and used inside the method to customize a response.

Understanding Constructors

A constructor in Apex that is invoked if an object is created from a class. Constructors are useful to operate class properties and put up the required state of a new object.

Creating a Default Constructor

If no constructor is explicitly or manually defined, Apex is providing a no-argument constructor. For clarity, a default constructor will be able to define explicitly:

public class Person {
    public String name;
    public Integer age;
    
    // Default constructor
    public Person() {
        name = 'Unknown';
        age = 0;
    }
}

If an instance of the Person class is created by using the default constructor then the name is set to ‘Unknown’ and age is set to 0.

Parameterized Constructors

Parameterized constructors will permit the initialization of an object property using parameters provided at the time of creation. Below is an example:

public class Person {
    public String name;
    public Integer age;
    
    // Parameterized constructor
    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
}

 

In the parameterized constructor, the keyword this is useful to refer to the current instance’s variables. Above constructor allows the creation of a Person object with specific values:

// Creating an instance of Person with parameterized values
Person person1 = new Person('Apex Learning', 30);
System.debug('Name: ' + person1.name + ', Age: ' + person1.age);
Parameterized Constructors
The use of above constructors provide flexibility by letting different instances of a class be initialized with different values.
Also Read

Don’t forget to checkout: DML Operations and Exception Handling in Apex.

Access Modifiers in Apex

Access modifiers will control the visibility of classes, methods and variables in Apex. Selecting the correct access modifier will make sure that code is secure and only accessible where it is required.

Public Modifier

The public modifier lets a class, method or variable to be accessible by any other Apex code in the same namespace or in managed packages, the code is also declared as global if it is in a managed package. Public access is generally used for classes and methods that are considered for common use.

public class Utility {
    public static String getGreeting() {
        return 'Hello, Salesforce!';
    }
}

In the above example, the Utility class and method getGreeting() are accessible to any other code that bring in this class.

Private Modifier

The private modifier restricts access to inside the defining class only. It will be useful for variables and methods that are required to be used only inside the class and not covered outside.

public class Calculator {
    // Private method accessible only within this class
    private Integer add(Integer a, Integer b) {
        return a + b;
    }
    
    // Public method that uses the private add method
    public Integer getSum(Integer a, Integer b) {
        return add(a, b);
    }
}

In the above piece of code the method add() is private to make sure that it cannot be accessed directly from outside the class. The public method getSum() uses this private method to perform the addition.

Global Modifier

The global modifier is the top level of access and is useful when we need classes, methods or variables to be accessible within different namespaces, including those in other managed packages. Global modifier is used when developing applications required for broad distribution.

global class GlobalUtility {
    global static String getGlobalGreeting() {
        return 'Hello from Global Utility!';
    }
}

The GlobalUtility class and its method getGlobalGreeting() are accessible from any code, even from outside the package.

Best Practices for Apex Classes, Methods and Constructors

Below are some best practices when working with classes, methods and constructors:

  1. Keep Classes Focused: Any class should have a single task to work upon.
  2. Use Meaningful Names: Choose proper names for classes, methods and variables.
  3. Document Code: Include comments to explain complex logic or decisions.
  4. Access Control: Always use the appropriate access modifier as per business needs.
  5. Simplify Constructors: Avoid complex logic in constructors.
  6. Test Classes: Write unit tests to verify the behavior of our classes, methods and constructors.

Conclusion

Apex classes, methods, access modifiers and constructors are the fundamental building blocks for developing on the Salesforce platform. The above article has covered how to create a class, define methods and constructors, and use various access modifiers to control visibility. By applying these concepts, developers can create efficient and maintainable code that matches the best practices.

This is Day 7 of the Apex 10-Day Series:How to Create and Use Apex Classes, Methods and Constructors.

On Day 8, we’ll explore Triggers in Apex in detail. Stay tuned and happy coding!

Written by

user

Mohit Bansal

Salesforce Technical Architect | Lead | Salesforce Lightning & Integrations Expert | Pardot | 5X Salesforce Certified | App Publisher | Blogger

Contributor of the month
contributor
Gopinath G

Passionate about the intersection of cutting-edge technologies

Get the latest tips, news, updates, advice, inspiration, and more….

...
Boost Your Brand's Visibility

Want to promote your products/services in front of more customers?

...