Salesforce Menu

Method Overriding in Apex

If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Apex.
In other words, If subclass provides the specific implementation of the method that has been provided by one of its parent class, it is known as method overriding.

Usage of Apex Method Overriding

Method overriding is used to provide specific implementation of a method that is already provided by its super class. Method overriding is used for runtime polymorphism

Rules for Apex Method Overriding

  • method must have same name as in the parent class

  • method must have same parameter as in the parent class.

  • must be IS-A relationship (inheritance).

  • Systax for Method Override

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

    public class Child extends Parent{
      public override void display(){
        System.debug(‘This is form Child’);
      }
    }

    Child ch = new Child();
    ch.display();

    Output :

    Subscribe Now