
What are classes in Apex programming?

Table Of Contents
- What is the private Access Specifier in
- What is the public Access Specifier in Apex?
- What is the global Access Specifier in Apex?
- What is the protected Access Specifier in Apex?
- What is a class in Apex programming, and why is it important?
- What are the key components of a class in Apex?
- How does inheritance work with classes in Apex?
- How can I organize multiple classes in the same Apex file?
In Apex programming, classes are the foundation of object-oriented design. They allow me to create robust and reusable code structures. A class serves as a blueprint for defining objects. It encapsulates both data and behavior within a single entity. By using classes, I can group related attributes and functions together. This enhances code organization and improves maintainability. I can model real-world entities in my applications. This makes it easier to understand and manage complex business logic.
Classes in Apex are essential for using the benefits of encapsulation, inheritance, and polymorphism. Encapsulation protects the internal state of an object by restricting access to its fields and methods. Inheritance enables me to create new classes that inherit properties from existing ones. This relationship promotes code reuse and reduces redundancy. It helps me build applications more efficiently. As I dive deeper into Apex programming, understanding how to define and use classes will enhance my ability to create scalable and maintainable solutions within the Salesforce
Syntax:
private | public | global | Protected // Access specifier
[virtual | abstract | with sharing | without sharing] // Access specifier
class ClassName [implements InterfaceNameList] [extends ClassName] {
// Classs Body
}
Read more: Interfaces in Salesforce
Example:
public class ApexDemoController{
Public static void updateContact(){
// variable declaration
List<Contact> conList = new List<Contact>();
// SOQL query
conList = [Select Id,FirstName,LastName from Contact Where LastName = 'Test'];
List<contact> listToUpdate = new List<Contact>();
// iteration over contact list
for(contact con:conList){
con.Title = 'Manager';
listToUpdate.add(con);
}
// flow control statement
if(listToUpdate != null || listToUpdate.size()> 0 ){
// DML statement
update listToUpdate;}
}
}
}
Let’s take a look at Apex Access Specifiers:
Following are the apex modifiers supported by the apex.
1. What is the private Access Specifier in Apex?
The private access specifier in Apex allows me to limit the visibility of methods, variables, and constructors to only within the same class. When I mark a variable or method as private, it means no other class, even subclasses, can access it. This provides strong encapsulation, ensuring that other parts of my code cannot accidentally or intentionally interfere with sensitive logic or data. It’s especially useful when I want to control access and avoid unintended modifications to critical portions of my code.
For example, I might use the private keyword when dealing with internal calculations or sensitive data fields. Here’s a simple example:
public class Employee {
private String name;
private Integer age;
public Employee(String name, Integer age) {
this.name = name;
this.age = age;
}
private void calculateSalary() {
// Internal logic for salary calculation
}
}
In this case, both the name
and age
fields, as well as the calculateSalary
method, are only accessible within the Employee
class. This allows me to protect internal data and business logic from external access.
2. What is the public Access Specifier in Apex?
The public access specifier provides open access to the code across my entire Salesforce organization. If I declare a class, method, or variable as public, any other class can access it without restriction, as long as they are within the same org. This is great when I want to make certain functionality broadly available across different classes or systems within my Salesforce environment.
I often use public access for common utility methods or services that other developers or processes within the same org will use. Here’s a simple example:
public class MathOperations {
public Integer addNumbers(Integer a, Integer b) {
return a + b;
}
}
Here, the addNumbers
method is available to any class in the org. This allows me to reuse common operations, like adding numbers, across various parts of my system without duplicating code.
3. What is the global Access Specifier in Apex?
The global access specifier in Apex opens up a class or method for external access, even beyond my Salesforce org. This is particularly useful when I’m building managed packages or apps that need to be accessed by different orgs or external systems. I might also use it for APIs that need to be called by external code. Essentially, global provides the highest level of visibility in Apex, but I must use it carefully to avoid exposing too much of my internal logic.
When using the global specifier, I ensure that only the necessary methods or classes are exposed to external systems. Here’s an example:
global class ExternalService {
global void processOrder(String orderId) {
// Process the order for external system
}
}
In this example, the processOrder
method can be accessed from outside the org, making it suitable for integration with external services. I should note that global should be used sparingly to avoid exposing too much of my internal structure to external systems.
4. What is the protected Access Specifier in Apex?
The protected access specifier in Apex provides a balance between private and public access, specifically designed for use in inheritance. When I declare a field or method as protected, it becomes accessible within the class and its subclasses (even if those subclasses are in a different package). This is useful when I want to allow some level of control to subclasses but still keep the member hidden from other classes.
For instance, when I’m working on a parent class and want to share some data with child classes, I’ll mark those fields or methods as protected. Here’s a quick example:
public class Vehicle {
protected String fuelType;
public Vehicle(String fuel) {
this.fuelType = fuel;
}
protected void refuel() {
System.debug('Refueling ' + fuelType);
}
}
public class Car extends Vehicle {
public Car(String fuel) {
super(fuel);
}
public void startEngine() {
refuel();
System.debug('Engine started');
}
}
In this case, the fuelType
variable and refuel
method are protected in the Vehicle
class, meaning they’re available for use by the Car
class, but not by any external class. This helps me to share logic between related classes while keeping it hidden from other parts of the system.
Frequently Asked Questions(FAQs)
1. What is a class in Apex programming, and why is it important?
A class in Apex is a fundamental building block in programming. It serves as a template or blueprint for creating objects. In Apex, objects represent real-world entities, and classes define the properties (variables) and behaviors (methods) that those objects can have. For example, if I were building an application to manage employees, I would create an Employee
class that defines fields like name, age, and salary, as well as methods to calculate their performance or bonus.
Classes are essential because they allow me to follow object-oriented programming (OOP) principles like encapsulation, inheritance, and polymorphism. By organizing the code into classes, I make it more modular, reusable, and easier to maintain. Without classes, it would be challenging to structure complex applications in a meaningful way. The use of classes enables me to break down the code into manageable components, allowing for better debugging and understanding.
2. How do I define a class in Apex?
Defining a class in Apex is straightforward. I start with the class
keyword, followed by the class name and a set of curly braces to define its body. Inside the class, I can define fields, constructors, and methods. Fields represent the data attributes of the object, constructors are used to initialize the objects, and methods define the behavior. Here’s a simple example of how I would define a class in Apex:
public class Employee {
public String name;
public Integer age;
public Employee(String name, Integer age) {
this.name = name;
this.age = age;
}
public void displayInfo() {
System.debug('Name: ' + name + ', Age: ' + age);
}
}
In this example, the class Employee
has two fields (name
and age
), a constructor to initialize the fields, and a method (displayInfo
) to display the information. By defining the class in this way, I make it easier to create employee objects and manage their data efficiently.
3. What are the key components of a class in Apex?
The key components of a class in Apex include fields, methods, constructors, and, optionally, inner classes. Fields represent the data attributes of the object and store information like text, numbers, or other data types. Methods define actions that objects of the class can perform. These methods can take parameters, perform operations, and return values. Constructors are special methods used to initialize objects when they are created, allowing me to set the initial state of the object.
Additionally, I can have inner classes within a class. These are classes defined inside another class and are used when I want to group related functionality together but don’t want to expose the inner workings to the rest of the system. Each component plays a role in how the class interacts with the rest of my code, making the class a powerful and versatile tool for object-oriented design in Apex.
4. What is the purpose of a constructor in an Apex class?
The main purpose of a constructor in an Apex class is to initialize objects when they are created. When I create an object from a class, the constructor sets up the initial values of the object’s fields. If I don’t define a constructor, Apex provides a default no-argument constructor. However, I can also define my own constructors to initialize fields with specific values when the object is created. This allows me to ensure that every object starts in a valid and consistent state.
For instance, if I want to create an Employee
object with a name and age, I can define a constructor like this:
public Employee(String name, Integer age) {
this.name = name;
this.age = age;
}
This constructor ensures that every time I create an Employee
object, it will have a name and age. Constructors give me control over how objects are initialized and can help me enforce certain rules, like ensuring that important fields are always set during object creation.
5. How can I create objects using a class in Apex?
To create objects using a class in Apex, I use the new
keyword, followed by the class name and parentheses, which may contain arguments for the constructor. When I create an object, the constructor of the class is called, and the fields of the object are initialized with the values I pass in. Objects allow me to interact with the data defined in the class, calling methods, and accessing or modifying fields as needed.
For example, using the Employee
class defined earlier, I can create an object like this:
Employee emp = new Employee('John Doe', 30);
In this case, the Employee
object emp
is created with the name John Doe
and age 30
. I can then call methods on the object or access its fields, like emp.displayInfo()
. Creating objects is the core of working with classes, as it allows me to instantiate and work with real instances of the template defined by the class.
6. What is the difference between instance methods and static methods in a class?
Instance methods are methods that operate on individual objects of a class. They require an instance of the class to be called. I can define instance methods when the behavior or operation depends on the specific values of the object’s fields. These methods are called on an object of the class, and they can access and modify the object’s fields. For example, the displayInfo()
method in the Employee
class is an instance method because it operates on the fields name
and age
of a specific Employee
object.
Static methods, on the other hand, do not operate on an instance of the class. Instead, they belong to the class itself. Static methods can be called without creating an object, and they cannot access instance fields directly. I use static methods when I want to perform an operation that is related to the class but doesn’t depend on the state of any particular object. Here’s an example:
public class MathOperations {
public static Integer addumbers(Integer a, Integer b) {
return a + b;
}
}
I can call this static method without creating an object of MathOperations
, like this: MathOperations.addNumbers(2, 3);
. Static methods are useful for utility functions that perform common tasks without needing an object.
7. How does inheritance work with classes in Apex?
Inheritance is a powerful feature of object-oriented programming that allows me to create a new class based on an existing class. This means that the new class, often called a subclass or child class, inherits all the properties and methods of the existing class, referred to as the superclass or parent class. By using inheritance, I can promote code reusability and create a hierarchical relationship between classes. This structure helps me to build more complex systems while maintaining simplicity in my code.
For instance, if I have a class called Vehicle
, I can create subclasses like Car
and Truck
that inherit from Vehicle
. This allows Car
and Truck
to have all the characteristics of Vehicle
, such as methods for starting or stopping, while also allowing them to have their own unique properties or behaviors. Here’s an example:
public class Vehicle {
public void start() {
System.debug('Vehicle is starting');
}
}
public class Car extends Vehicle {
public void honk() {
System.debug('Car is honking');
}
}
In this example, the Car
class inherits the start
method from the Vehicle
class. When I create an instance of Car
, I can call both the inherited start
method and the honk
method defined specifically for Car
. Inheritance helps me streamline my code and reduce redundancy, allowing me to build on existing functionality.
8. Can an Apex class have multiple constructors? If so, how?
Yes, an Apex class can have multiple constructors, a feature known as constructor overloading. This allows me to define more than one constructor with different parameter lists, enabling the creation of objects in various ways based on the input I provide. By providing multiple constructors, I can offer flexibility in how I initialize my class, allowing for different use cases while maintaining the same class structure.
For instance, I could define an Employee
class with one constructor that takes both name
and age
, and another constructor that only takes name
, setting a default age. Here’s an example:
public class Employee {
public String name;
public Integer age;
// Constructor with both name and age
public Employee(String name, Integer age) {
this.name = name;
this.age = age;
}
// Constructor with only name, defaulting age to 25
public Employee(String name) {
this.name = name;
this.age = 25;
}
}
In this example, I can create an Employee
object either by providing both name and age or just the name, in which case the age defaults to 25. This flexibility enhances usability, allowing other developers (or myself) to instantiate the class with the most relevant data.
9. What is an inner class in Apex, and when should I use it?
An inner class in Apex is a class defined within another class. Inner classes are useful for logically grouping classes that will only be used in one place, helping to keep my code organized and encapsulated. By using inner classes, I can create a relationship between the outer and inner classes, allowing the inner class to access the fields and methods of the outer class. This can lead to cleaner code, especially in cases where a class is tightly coupled to another.
I typically use inner classes when I want to create utility classes that are relevant only within the scope of the outer class. For example, if I have a class representing a company, I might have an inner class for Employee
that is specific to that company. Here’s a quick example:
public class Company {
public class Employee {
public String name;
public Integer age;
public Employee(String name, Integer age) {
this.name = name;
this.age = age;
}
}
}
In this example, the Employee
class is an inner class of Company
. This signifies that Employee
is only relevant within the context of Company
. If I were to use Employee
in other parts of my code, I would need to reference it as Company.Employee
. This organization helps me manage related classes effectively.
10. How can I organize multiple classes in the same Apex file?
Organizing multiple classes in the same Apex file is possible, but there are some guidelines to follow. In Apex, I can define one top-level class in a file, and if I want to include additional classes, they must be inner classes or private classes within the top-level class. This means I can have a structure where one public class is the main class, and other classes that are closely related can be defined as inner classes or as private classes that are accessible only within the same file.
For example, if I have a main class called School
, I can include an inner class for Student
:
public class School {
public class Student {
public String name;
public Student(String name) {
this.name = name;
}
}
private class Teacher {
public String name;
public Teacher(String name) {
this.name = name;
}
}
}
In this example, School
is the top-level class, while Student
is an inner class that can be accessed publicly. The Teacher
class is a private class, meaning it can only be accessed within the School
class. By organizing classes in this way, I can keep related functionality together, making my code easier to understand and maintain.
CRS Info Solutions offers a comprehensive and dynamic Salesforce online course career building program for beginners, covering admin, developer, and LWC concepts and essential Salesforce interview questions, thorough certification preparation, and strategic job prep guidance.
Next chapter Methods in Salesforce Apex.