Salesforce Menu

Inheritance in Apex

Inheritance in Apex is a mechanism in 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. When you inherit from an existing class, you can reuse methods and fields of parent class, and you can add new methods and fields also.
Inheritance represents the IS-A relationship, also known as parent-child relationship.

Why use inheritance in Apex?

  • For Method Overriding (so runtime polymorphism can be achieved).

  • For Code Reusability.

Syntax Apex inheritance

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

Syntax of Sub class

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

Create an object and call method

Child c = new Child();;

Output :

Subscribe Now