Free Salesforce Developers Tutorials >

Chapter 4 - Object Oriented Programming >

Object Oriented Programming

Object Oriented Programming

What You’ll Learn

What is Apex Class? What is Apex Class?

Syntax of Apex ClassSyntax of Apex Class

What are Apex Variable?What are Apex Variable?

Syntax of Apex VariableSyntax of Apex Variable

Syntax of defining a Method in ApexSyntax of defining a Method in Apex

How to Pass Values to Apex Class MethodsHow to Pass Values to Apex Class Methods:

What are Access Modifiers in Apex?What are Access Modifiers in Apex?

What are Static and Instance variables and methods?What are Static and Instance variables and methods?

What are contructors in Apex?What are contructors in Apex?

How to define a constructor in Apex?How to define a constructor in Apex?

What are Init or Initialization Blocks?What are Init or Initialization Blocks?

What are Static and Instance Initialization Blocks?What are Static and Instance Initialization Blocks?

What are Abstract Class in Apex?What are Abstract Class in Apex?

Syntax of using Abstract Class in ApexSyntax of using Abstract Class in Apex

What is Inheritence in Apex?What is Inheritence in Apex?

How to do inheritence in Apex?How to do inheritence in Apex?

What is a Virtual Class in Apex?What is a Virtual Class in Apex?

Syntax of using Virtual Class in ApexSyntax of using Virtual Class in Apex

What is a Interface in Apex?What is a Interface in Apex?

Syntax of using Interface in ApexSyntax of using Interface in Apex

What is Apex Class?

An Apex Class is a template or blueprint from which objects are created. It is similar to a Java class and has variables and methods. Variables can contain the data and methods have the logic that act upon that data.

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 ] [virtual | abstract | with sharing | without sharing] class ClassName [implements InterfaceNameList] [extends ClassName] 
// The body of the class

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
public class NewCarModel{
	// class variable
	public static String model = '';
	public void drive(){
		//method variable
		Integer speed = 50;
		//class variable can be accessed in the method

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


[public | private | protected | global] [final] [static] data_type variable_name 
[= value]


private Integer i, j, k;
String helloStr = 'Hello World';
public static final Integer DISCOUNT = 10;

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


// public method with Integer as return type
public Integer maxSpeed(){
	System.debug('Max Speed'); 
	return 100;
Integer i = maxSpeed();

Salesforce Developer

How to Pass Values to Apex Class Methods?

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.


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
    // 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();; // instance xyz 5
obj1.zzz(); // Error: Static method cannot be referenced.
System.debug(ob1.i); // 5
System.debug(obj1.s); // error; // error
Abc.zzz(); // static zzz hello
System.debug(Abc.i); // error
System.debug(Abc.s); // hello

A static variable can’t be accessed through an instance of that class.

The same is true for instance methods. To access any class method variable directly, they should be public.


Class’s static variable or static method cannot be accessed through an instance of that class.

Inner Class:

In Apex, you can define a class in a class which is called as inner class.


public class Outer {
class Inner {}


Inner class is by-default private.

Singleton Class

A class which can only have a single object.

Access Modifiers

Apex allows you to use private, public, protected and global access modifiers when defining methods and variables.

By default a method or a variable is visible only to the apex code within the defining class. You must explicitly specify a method or a variable as public in order for it to be available to other classes in the same application namespace.

Types Of Access Modifiers 

1. Private

This is the default access modifier for the methods and variables.Methods and variables defined as private are accessible only within the apex class in which it is defined. If you do not specify any access modifier then it is by-default private.

public class OOPS
Integer a=5;
void OOPsInstance()
	System.debug(‘OOPs Instance’);
void callInstance()
public void callInstance()
} // in this manner private methods can be called.

2. Protected

The method/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.


You can use it only 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

Global means 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. 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.

If you declare a method or a variable as global you must also declare the class that contains it as global.


It is not recommended to use global access modifier because cross-application dependencies are difficult to maintain.


  • A constructor contains a code that invokes when an object is created. We don’t need a constructor for every class.
  • If a class doesn’t have a user-defined constructor, a default no argument public constructor is used.
  • Once you create a constructor you no longer access to default no argument public constructor.
  • Constructor is method having the same name of class.
  • Constructor returns Nothing.


class Account
String acc_name;
String acc_number;
Decimal acc_balance;


A class can have multiple constructors.

public class Money
Integer rs, paisa;
public Money() // Default constructor
rs=0; paise=0;
public Money(integer r, integer p) // Parameterized constructor
rs =r; paisa=p;
public Money(Money m1) // Copy Constructor
{; paisa=m1.paisa;
public void show()
	System.debug(‘Rupees = ’ + rs + ’ Paise = ’ + paisa);

Anonymous Code:

Money m1= new Money();; // Rupees = 0 Paise = 0
Money m2= new Money(100, 50);; // Rupees = 100 Paise = 50
Money m3= new Money(m2);; // Rupees = 100 Paise = 50

‘this’ variable

Keyword ‘this’ can be used to refer current class instance variable.


public Money(integer rs, integer paisa) // Parameterized constructor
{ = rs; 
this.paisa = paisa;

‘this’ method

It is used to call the other constructors of the same class and it should be the first statement of the block.


public class Money
Integer rs, paisa;
public Money() // Default constructor
public Money(integer r, integer p) // Parameterized constructor
rs =r; 
public Money(Money m1) // Copy Constructor
this(, m1.paisa);

Salesforce certifications

Initialization Blocks

  • The instance initialization block in class is executed each time an object is instantiated from that class.
  • It is executed even before a constructor.
  • We can have multiple initialization blocks.
  • They are executed in the order they are written in the class.

Types Of Initialization Blocks

1. Instance Initialization Blocks

The instance initialization block in a class is executed each time an object is instantiated from that class.

2. Static Initialization Blocks

Static Block precedes to the keyword static and runs only once regardless of how many times you access the class that contains.

Class can have any number of instance initialization block, they can appear anywhere in the code and the blocks are executed in the order in which they appear in the file.


public class Account
String name;
String number;
Double balance;

Static {
	System.debug(‘Static 1’);
Static {
	System.debug(‘Static 2’);

public Account()
	System.debug(‘Instance 1’);
	System.debug(‘Instance 2’);
// Order of execution: S1 S2 I1 I2 C I1 I2 C


public virtual class SuperClass
private integer one;
protected integer two;
public integer three;
private void method1()
   System.debug(‘I am method 1 of super class’);
protected void method2()
   System.debug(‘I am method 2 of super class’);
public void method3()
  System.debug(‘I am method 3 of super class’);

Overridden methods can not have more restrictive access modifier as of their superclass method.

public class MainClass {
    System.debug(; // It is private which can not be accessed
    // outside the class.		
    System.debug(s1.two); // Protected which can only be accessed in that class
    // in which it is declared and the class
    // which extends it
    System.debug(s1.three); // public,ok


  • In Apex, classes are by-default final so to extend the class we need to declare it with ‘virtual’ keyword.
  • Whereas in methods if we want to override a method then that method needs to declared as virtual.
  • If a method is declared as virtual then the subclass’s method needs to be declared with  override keyword in order to override that virtual method.
  • Classes can never be protected or private.

‘super’ Keyword

Super method is used to call the method of a superclass. It needs to be the first statement in the constructor of a subclass.

public class Animal {
    String color = "white";
public class Dog extends Animal {
    String color = "black";
    void printColor() {
        System.out.println(color); // prints color of Dog class  
        System.out.println(super.color); // prints color of Animal class  

Abstract Class

  • Abstract is itself virtual.
  • Abstract class can have static methods but static methods can not be abstract as they cannot be overridden.
  • Abstract classes can have constructors, instance variables and initialization blocks which will be utilized by the object of subclass.
  • Abstract methods can not be final.
  • If you want to override non abstract method from an abstract class make sure to declare it with the virtual keyword.
  • We cannot create object of an abstract class but we can create its reference.

public abstract class AbstractClass {
        Public abstract void method1() {}
        Public void method2() {
            System.debug(‘i 'm not abstract.’);
        Public class SubAbstractClass extends AbstractClass() {
                Public override void method1() {
                    System.debug(‘i\ 'm overridden by SubAbstractClass’);


public interface Animal {
                    void speak();
                    void eat();
                public class Cat() {
                    public void speak() {
                    public void eat() {

  • Interfaces in apex can not have variables.
  • We can not use public or abstract explicitly while defining the methods of interfaces in Apex.
  • In Apex, no two classes or interfaces can exist in a single file.
  • We do not need to use the override keyword to override the interface methods.
  • If there is a class that has the same name or signature as of the interface method then we need to use the override keyword in a subclass to override the method.
  • Interfaces can not have constructors.
  • Interfaces cannot have static methods as the methods are by default abstract.
  • If a method is not public then it is by-default private and if this method is abstract then it has to be defined in the subclass.
  • Protected methods can only exist in virtual class and abstract class.
  • Protected methods can be defined in a class which is not virtual.

Download Study Material

Get access to exclusive study material for Salesforce Certification and ace your exams!

Download Now

Our Salesforce Certification Courses

Hey there! Glad you made it through our Salesforce Developer Training for beginners . But wait! We've got some high-in-demand Salesforce courses for you to take your Salesforce skills to the next level, making you a desired professional in the Salesforce job market.

Post a Comment

Your email address will not be published. Required fields are marked *