Skip to main content

Apex Classes, Methods, and Interfaces

Apex is an object-oriented programming language used in Salesforce. Understanding classes, methods, and interfaces is essential for writing reusable, scalable, and maintainable code.

1. Apex Class

A class is a blueprint that defines variables (fields) and functions (methods). In Apex, all code must reside in a class.

Syntax:

        public class ClassName {
            // Variables
            // Methods
        }        
        
Example:

        public class Car {
            public String brand;
            // Constructor
            public Car(String carBrand) {
                brand = carBrand;
            }
            // Method
            public void displayBrand() {
                System.debug('Brand: ' + brand);
            }
        }             
        
Usage:

        Car c = new Car('Tesla');
        c.displayBrand(); // Output: Brand: Tesla
        

2. Apex Method

A method is a block of code that performs a specific task. It can return a value (or not) and can be public, private, static, etc.

Method Types:

Instance Method: Called on an object

Static Method: Called on a class (no object needed)

Example: Instance & Static

        public class MathUtils {
            // Static Method
            public static Integer square(Integer x) {
                return x * x;
            }
        
            // Instance Method
            public Integer cube(Integer x) {
                return x * x * x;
            }
        }        
        
Usage:

        System.debug(MathUtils.square(4));  // Output: 16
        MathUtils mu = new MathUtils();
        System.debug(mu.cube(3));           // Output: 27
        

3. Apex Interface

An interface defines a set of method signatures without implementation. Classes that implement the interface must define those methods.

Why Use It?

Enforces structure

Enables loose coupling and polymorphism

Used in Batch Apex, Queueable, and Trigger design patterns

Syntax:

        public interface Vehicle {
            void start();
            void stop();
        }        
        
Class Implementing Interface:

        public class Bike implements Vehicle {
            public void start() {
                System.debug('Bike started');
            }
        
            public void stop() {
                System.debug('Bike stopped');
            }
        }             
        
Usage:

        Vehicle v = new Bike();
        v.start();  // Output: Bike started
        v.stop();   // Output: Bike stopped 
        

Summary Table

Concept Purpose Example
Class Blueprint for objects public class Car {}
Method Function inside class public void drive()
Interface Contract that classes must follow implements Vehicle