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:
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(); c.show(); c.display();
Output :
This is from child
This is Parent