OOPS in Apex

Object-Oriented Programming (OOP) in Apex: Complete Guide

Object-Oriented Programming (OOP) in Apex: Complete Guide

1. Encapsulation

Definition: Bundling data (properties) and methods (behaviors) into a single unit (class) while restricting direct access to some components.

Purpose: Protect data integrity and control access via methods.

public class BankAccount {
    private String accountNumber;
    private Decimal balance;

    public void deposit(Decimal amount) {
        if (amount > 0) balance += amount;
    }

    public Decimal getBalance() {
        return balance;
    }
}

Key Points:

  • Use private variables to hide data.
  • Expose controlled access via public methods.

2. Classes and Objects

Class: Blueprint for creating objects (e.g., BankAccount).

Object: Instance of a class (e.g., BankAccount acc = new BankAccount();).

public class Car {
    public String model;
    public Integer year;

    public void display() {
        System.debug('Model: ' + model + ', Year: ' + year);
    }
}

Car myCar = new Car();
myCar.model = 'Tesla Model 3';
myCar.year = 2023;
myCar.display(); // Output: Model: Tesla Model 3, Year: 2023

3. Inheritance

Definition: A child class inherits properties/methods from a parent class.

Apex Limitation: Single inheritance only (one parent class).

public virtual class Vehicle {
    public virtual void start() {
        System.debug('Engine started');
    }
}

public class ElectricCar extends Vehicle {
    public override void start() {
        System.debug('Battery powered on');
    }
}

ElectricCar tesla = new ElectricCar();
tesla.start(); // Output: Battery powered on

Key Points:

  • Use virtual in parent class to allow method overriding.
  • Use extends for inheritance.

4. Polymorphism

Method Overriding

public class Animal {
    public virtual void makeSound() {
        System.debug('Generic animal sound');
    }
}

public class Dog extends Animal {
    public override void makeSound() {
        System.debug('Bark!');
    }
}

Dog d = new Dog();
d.makeSound(); // Output: Bark!

Method Overloading

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

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

Calculator calc = new Calculator();
System.debug(calc.add(2, 3)); // 5
System.debug(calc.add(2, 3, 4)); // 9

5. Abstraction

Abstract Classes

- Cannot be instantiated directly.

- Define abstract methods (no implementation) that child classes must override.

public abstract class Shape {
    public abstract Double getArea();
}

public class Circle extends Shape {
    private Double radius;
    public Circle(Double r) { radius = r; }

    public override Double getArea() {
        return Math.PI * radius * radius;
    }
}

Circle c = new Circle(5);
System.debug(c.getArea()); // 78.54

Interfaces

- Define method signatures (no implementation).

- Classes can implement multiple interfaces.

public interface Shape {
    Double getArea();
    Double getPerimeter();
}

public class Circle implements Shape {
    private Double radius;
    public Circle(Double r) { radius = r; }

    public Double getArea() {
        return Math.PI * radius * radius;
    }

    public Double getPerimeter() {
        return 2 * Math.PI * radius;
    }
}

Circle c = new Circle(5);
System.debug(c.getPerimeter()); // 31.415

6. Access Modifiers

Modifier Scope
private Within the defining class (default)
protected Defining class + subclasses
public Anywhere in the same namespace
global Across all namespaces (managed packages)
public class AccessExample {
    private String secret = 'Confidential';
    protected String internalCode = 'X123';
    public String info = 'Public Data';

    public void showData() {
        System.debug(secret); // Accessible
    }
}

7. Static Variables/Methods/Blocks

- Static Variables: Shared across all class instances.

- Static Methods: Called on the class, not instances.

- Static Blocks: Execute once when the class is loaded.

public class AppConfig {
    public static String environment = 'Production';

    static {
        System.debug('Loading app config...');
    }

    public static void logEnvironment() {
        System.debug('Environment: ' + environment);
    }
}

// Usage
AppConfig.logEnvironment(); // Output: Environment: Production

8. Constructors

- Default Constructor: Automatically created if none defined.

- Parameterized Constructor: Initialize objects with specific values.

- Constructor Chaining: Use this() to call another constructor.

public class Student {
    public String name;
    public Integer age;

    public Student() {
        this('Unknown', 0); // Calls parameterized constructor
    }

    public Student(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
}

Student s1 = new Student(); // Uses default
Student s2 = new Student('John', 25);

9. Initialization Blocks

- Instance Blocks: Run each time an object is created.

- Static Blocks: Run once when the class is loaded.

public class Demo {
    {
        System.debug('Instance block executed');
    }

    static {
        System.debug('Static block executed');
    }
}

// Execution Order:
// 1. Static block
// 2. Instance block
// 3. Constructor

10. Class Lifecycle

1. Static Initialization Blocks (once).

2. Instance Initialization Blocks (per object).

3. Constructors (per object).

11. Inner Classes

- Defined within another class for logical grouping.

- Often used for wrapper classes or encapsulation.

public class Order {
    public class OrderItem {
        public String productId;
        public Integer quantity;

        public OrderItem(String id, Integer qty) {
            productId = id;
            quantity = qty;
        }
    }

    public void processItems(List items) {
        for (OrderItem item : items) {
            System.debug('Processing: ' + item.productId);
        }
    }
}

// Usage
Order.OrderItem item = new Order.OrderItem('P123', 2);
List items = new List{item};
new Order().processItems(items);

12. Interfaces (Multiple Inheritance)

- Apex allows a class to implement multiple interfaces.

- Interfaces define a contract for methods.

public interface Loggable {
    void log(String message);
}

public interface Auditable {
    void audit();
}

public class Transaction implements Loggable, Auditable {
    public void log(String msg) {
        System.debug('Log: ' + msg);
    }

    public void audit() {
        System.debug('Audit completed');
    }
}

13. Virtual & Override Keywords

- virtual: Allows a method/property to be overridden.

- override: Indicates a method is overriding a parent’s implementation.

public virtual class Payment {
    public virtual void process() {
        System.debug('Processing payment');
    }
}

public class CreditCardPayment extends Payment {
    public override void process() {
        System.debug('Processing credit card');
    }
}

14. Important Interview Questions

  1. What is the difference between abstract classes and interfaces?

    - Abstract classes can have both abstract and concrete methods; interfaces only declare method signatures.

    - A class can implement multiple interfaces but extend only one abstract class.

  2. When would you use a static variable?

    - To maintain a value shared across all instances (e.g., a counter).

  3. What is the purpose of the super keyword?

    - To call a parent class’s constructor or overridden method.

  4. How does Apex handle memory for objects?

    - Objects are garbage-collected when no longer referenced.

  5. Can you override a private method?

    - No. Only public or protected methods marked as virtual can be overridden.

Comments

Popular posts from this blog

Understanding Note and ContentNote Objects in Salesforce

System administrator gets logged out when they use 'Login as User'