Association In Apex Classes

What is the Association?

In object-oriented programming (OOPs), Association defines a relation or connection between two separate classes that are set up through their objects. Association indicates how objects know each other and how they are using each other’s functionality as per need.

In Apex programming we can achieve Association via two ways:


Note: As we have seen above, there are two ways to connect two classes either using IS-A-Relationship or HAS-A-Relationship what being a developer you need to understand in which scenario you have to use IS-A Relationship or HAS-A-Relationship.

Inheritance (IS-A-Relationship):

Inheritance in Apex is a mechanism by which one object acquires all the properties and behaviors of parent object.
The idea behind inheritance in Apex is that you can create new classes that are built upon existing classes. Whenever you inherit from an existing class, you can reuse methods and fields of parent / super class, as well as you can add new methods and fields also based on the requirements.

Why use inheritance in Apex?

  • For Method Overriding (to achieved runtime polymorphism).
  • For Code Reusability.

Terms used in Inheritance:

  • Class: A class is a concept/prototype/template of common properties, from which objects are created.
  • Child Class/Sub Class: Child class is a class which inherits the other class, known as child class. It is also called extended class, derived class, or sub class.
  • Parent Class/Super Class: Parent class is the class from which a subclass inherits the features. It is also called a Super class or a base class.
  • Virtual: The virtual modifier declares that this class allows for extension and overrides.
  • Override: You cannot override a method with the override keyword in the child class unless the class and method have been defined as virtual.
  • Syntax Apex inheritance

    public virtual class Parent{
      public void display(){
        System.debug(‘This is Parent’);


    Syntax of Sub/Child class

    public class Child extends Parent{
      public void display show(){
        System.debug(‘This is from Child’);


    Create an object and call method

    Child c = new Child();;


    Output :

    This is from child
    This is Parent

    Subscribe Now