Object-Oriented Programming in Apex

Share

Classes & Methods

What Is a Class in Apex?

A class is a blueprint that defines behavior (methods) and data (variables).

Simple Explanation

A class is like a recipe, and methods are the steps.


Code Example

public class Car {
    public void drive() {
        System.debug('Car is moving');
    }
}

What Is a Method?

A method is a function inside a class that performs an action.

Car myCar = new Car();
myCar.drive();

Gist (Quick Revision)

Classes group logic, methods perform actions.


Access Modifiers

What Are Access Modifiers?

Access modifiers control who can access a class, method, or variable.

Common Access Modifiers

  • public – Accessible within org

  • private – Accessible only inside class

  • protected – Accessible in subclass

  • global – Accessible everywhere (used in APIs)


Real-Life Example

Think of access modifiers like house access:

  • private → bedroom

  • public → living room

  • global → front gate


Code Example

public class AccountService {
    private Integer count;
}

Gist (Quick Revision)

Access modifiers control visibility and security.


Static vs Instance Members

Instance Members

  • Belong to an object

  • Require object creation

Car car1 = new Car();

Static Members

  • Belong to the class

  • No object required

public class MathUtil {
    public static Integer add(Integer a, Integer b) {
        return a + b;
    }
}
Integer sum = MathUtil.add(5, 3);

Easy Rule to Remember

Static = Class-level
Instance = Object-level


Gist (Quick Revision)

Static members don’t need objects; instance members do.


Constructors & Method Overloading

What Is a Constructor?

A constructor initializes an object when it is created.

public class Student {
    public String name;

    public Student(String studentName) {
        name = studentName;
    }
}

What Is Method Overloading?

Method overloading allows multiple methods with the same name but different parameters.

public Integer add(Integer a, Integer b) {
    return a + b;
}

public Integer add(Integer a, Integer b, Integer c) {
    return a + b + c;
}

Real-Life Example

Same button, different functions based on input.


Gist (Quick Revision)

Constructors set values; overloading adds flexibility.


Inner Classes

What Is an Inner Class?

An inner class is a class defined inside another class.

Why Use Inner Classes?

  • Group related logic

  • Improve code organization

  • Hide implementation details


Code Example

public class OuterClass {
    public class InnerClass {
        public void show() {
            System.debug('Inside Inner Class');
        }
    }
}

Gist (Quick Revision)

Inner classes help organize and encapsulate related logic.

  • January 5, 2026