Object Oriented Programming
Chapter Topics
Object Oriented Programming in Apex is a powerful paradigm used extensively in modern software development, including Salesforce Apex. Understanding OOP concepts in Apex can significantly enhance your ability to write clean, efficient, and maintainable code in Salesforce.
What is Object Oriented Programming?
Object Oriented Programming in Apex is a programming paradigm that uses “objects” to design applications and computer programs. Objects are instances of classes, which can contain both data (attributes or properties) and methods (functions or procedures). OOP aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming.
OOP Concepts in Apex
Following are the OOPS concepts in Apex:
- Classes and Objects: Classes in Salesforce Apex are blueprints for creating objects. A class can contain fields, methods, constructors, and inner classes. An object is an instance of a class that contains real values instead of variables.
- Encapsulation: Encapsulation is the mechanism of restricting access to certain components and keeping the data safe within the class. It is typically achieved using access modifiers such as private, protected, public, and global.
- Inheritance: Inheritance is a mechanism wherein a new class inherits the properties and behavior of another class. It promotes code reusability and establishes a natural hierarchy between classes.
- Polymorphism: Polymorphism allows methods to do different things based on the object it is acting upon, even though they share the same name. It can be achieved through method overloading and method overriding.
Object Oriented Programming Benefits in Salesforce Apex
Using OOP concepts in Salesforce Apex provides numerous benefits:
- Modularity: Code can be organized into classes and objects, making it more manageable and modular.
- Reusability: Inheritance and polymorphism enable code reuse, reducing redundancy.
- Scalability: OOP principles help in building scalable applications that can grow and evolve over time.
- Maintainability: Encapsulation and modular design improve the maintainability of the codebase.
- Improved Debugging: Encapsulation ensures that objects control their own state, making debugging easier.
What is an Apex Class?
An Apex Class in Salesforce is a blueprint for creating objects that encapsulate data and behavior within the Salesforce platform. It allows developers to define the structure (properties) and behavior (methods) of Salesforce objects. Classes in Apex are essential for organizing and modularizing code, making it more reusable and maintainable.
Apex Class Syntax
Let’s understand the basic syntax of an Apex class. To define an Apex class, you need to specify a couple of keywords per the syntax given. Let’s understand each keyword and its use.
[ private | public | global | protected ] [virtual | abstract | with sharing | without sharing] class ClassName [implements InterfaceNameList] [extends ClassName]
{
// The body of the class
}
public class ClassName { // Fields (variables) public Integer field1; private String field2; // Constructor public ClassName() { // Initialization code field1 = 0; field2 = ‘Default’; } // Methods public void someMethod() { // Method logic System.debug(‘Hello, Apex!’); } } |
What Is Apex Class Variables?
Apex variables are of a specific data type and contain the data on which logic is performed. Apex class contains variables and methods. Variables in an apex class are also called class variables as they belong to the whole class. Individual methods in an Apex Class can also contain their own variables.
Apex Class Variable Syntax
The syntax of class and method variables is quite similar, the only difference is method variables cannot have any access modifiers. To declare or initialize a class variable, you need to specify the following:
- Access modifiers
- Definition modifier
- Data type of the variable
- Appropriate name to the variable
- Value to the variable
Syntax:
[public | private | protected | global] [final] [static] data_type variable_name [= value] |
Example:
public class ExampleClass { // Fields (instance variables) public Integer number; // Integer variable private String text; // String variable // Constructor public ExampleClass() { number = 10; text = ‘Hello, Apex!’; } // Method using local variables public void displayInfo() { Boolean isActive = true; // Boolean variable Decimal price = 99.99; // Decimal variable System.debug(‘Number: ‘ + number); // Output: Number: 10 System.debug(‘Text: ‘ + text); // Output: Text: Hello, Apex! System.debug(‘Is Active: ‘ + isActive); // Output: Is Active: true System.debug(‘Price: ‘ + price); // Output: Price: 99.99 } } |
What Is Apex Class Methods?
Apex Class Methods are defined in an Apex Class that provide logic to accomplish a particular task. Let’s examine the syntax of a method.
Syntax Of Apex Class Methods
[public | private | protected | global] [override] [static] data_type method_name (input parameters) { // The body of the method } Example: // public method with Integer as return type public Integer maxSpeed(){ System.debug(‘Max Speed’); return 100; } Integer i = maxSpeed(); |
Sometimes two methods need to communicate with each other and hence pass data so that a particular logic can be implemented properly. Let’s understand this concept with an example.
Example:
public class calculateClass { // method that calculates sum public static void calculateSum() { Integer i = 5; Double j = 6; // variables i and j passed to sumMethod as parameters Double k = sumMethod(i, j); // this will output the sum of i and j which is 11 System.debug(k); } // another method that does the actual calculation public static Double sumMethod(Integer a, Double b) { // add the values Double c = a + b; // return variable c which is a sum of a and b return c; } } public class Abc { Integer i=5; static string s = ‘Hello’; public void xyz() { System.debug(‘instance xyz ’ + i); } public static void zzz() { System.debug(‘static zzz ’ + s); } } Abc obj1 = new Abc(); obj1.xyz(); // instance xyz 5 obj1.zzz(); // Error: Static method cannot be referenced. System.debug(ob1.i); // 5 System.debug(obj1.s); // error Abc.xyz(); // error Abc.zzz(); // static zzz hello System.debug(Abc.i); // error System.debug(Abc.s); // hello |
How to Pass Values to Apex Class Methods?
Sometimes two Apex methods need to communicate with each other. For this they need to pass data so that a particular logic can be implemented properly.
Example:
public class calculateClass { // method that calculates sum public static void calculateSum() { Integer i = 5; Double j = 6; // variables i and j passed to sumMethod as parameters Double k = sumMethod(i, j); // this will output the sum of i and j which is 11 System.debug(k); } // another method that does the actual calculation public static Double sumMethod(Integer a, Double b) { // add the values Double c = a + b; // return variable c which is a sum of a and b return c; } } public class Abc { |
What are Access Modifiers?
Apex allows the user to use private, public, protected and global access modifiers while defining methods and variables. By default a method or a variable is visible only to the apex code within the defining class. If you wish for your method or variable to be public to other classes in the same application namespace, then you must specify it.
Types Of Access Modifiers
1. Private
The default access modifier for the methods and variables is set to Private. These methods and variables are only within the apex class in which it is defined.
public class calculateClass { // method that calculates sum public static void calculateSum() { Integer i = 5; Double j = 6; // variables i and j passed to sumMethod as parameters Double k = sumMethod(i, j); // this will output the sum of i and j which is 11 System.debug(k); } // another method that does the actual calculation public static Double sumMethod(Integer a, Double b) { // add the values Double c = a + b; // return variable c which is a sum of a and b return c; } } public class Abc { Integer i=5; static string s = ‘Hello’; public void xyz() { System.debug(‘instance xyz ’ + i); } public static void zzz() { System.debug(‘static zzz ’ + s); } } Abc obj1 = new Abc(); obj1.xyz(); // instance xyz 5 obj1.zzz(); // Error: Static method cannot be referenced. System.debug(ob1.i); // 5 System.debug(obj1.s); // error Abc.xyz(); // error Abc.zzz(); // static zzz hello System.debug(Abc.i); // error System.debug(Abc.s); // hello |
2. Protected
Using the protected modifier the method or variable is visible to any inner class in the defining apex classes and to the classes that extend the defining apex class. You can only use it for instance methods and member variables.
public class OOPS { protected integer a = 5; private integer b = 6; public integer c = 7; void privateMethod() { System.debug(‘A = ’ + a + ’ B = ’ + b + ’ C = ’ + c); } protected void protectedMethod() { System.debug(‘A = ’ + a + ’ B = ’ + b + ’ C = ’ + c); } public void publicMethod() { System.debug(‘A = ’ + a + ’ B = ’ + b + ’ C = ’ + c); } class OOPsInner { Integer ai = a; Integer bi = b; Integer ci = c; } } Anonymous Code: Oop = new OOPs(); oop.privateMethod(); // error oop.protectedMethod(); // error oop.publicMethod(); // 5,6,7+ Oop.a; // 7 Oop.b; // error Oop.c; // error Class name and object name can be same(in Apex Code and Java) i.e. the object can be created in the class itself. class OOPs { public static void main() { OOps oop = new OOps(); } } |
3. Public
The method or variable declared as public can be used by any apex in the application or namespace.
4. Global
When the method or variable can be used by any apex code that has access to the class not just the apex code in the same application, then it is set as Global Access Modifier. This access modifier should be used for any method that needs to be referenced outside of the application either in the API or by other apex code.
Next ChapterNeed more support?
Get a head start with our FREE study notes!
Learn more and get all the answers you need at zero cost. Improve your skills using our detailed notes prepared by industry experts to help you excel.