A constructor is a unique method that is used to create and initialize an instance/Object of a class. When an object is created from a class, the constructor is automatically called to initialize the object’s state and properties.
The constructor does not have any return type.
The name of the constructor must be the same as the Class Name.
The parent class(topmost class) constructor should always be public.
Private in cases where the methods are class methods.
Types of Constructor
There are two types of constructors in Salesforce:
Default Constructor: A default constructor is a constructor that is automatically created by Salesforce if no other constructor is defined in the class.
The default constructor takes no arguments and does not perform any initialization.
A parameterized constructor is a constructor that takes one or more parameters and uses them to initialize the object’s state and properties.
When you want to enforce that user must need to pass the value while creating the instance/Object.
Parameterized constructors are useful for setting initial values or default values for object properties.
Animal dog = new Animal(‘Paremrian’);
Conditional Statements
Conditional Statements
If else
Switch
Use the “if-else” statement in Apex code to execute different blocks of code based on a condition
Switch Statement in Salesforce
You can use the “switch” statement in Apex code to execute different blocks of code based on the value of a variable.
The syntax for the “switch” statement is as follows:
Here’s an example of how to use the “switch” statement in Apex code:
Hands-on Code
Assignment
Create a class “Car” that should have the following
The class should have the private variables
Name
Model
Year
Company
Type
Create multiple constructors that are accepting the different parameters
Within the constructors assign the values to the private variables. Note: – The value should be assigned to the variable that is passed in the constructor and for other variables assign a blank value. See the example below
Amit Singh aka @sfdcpanther/pantherschools, a Salesforce Technical Architect, Consultant with over 8+ years of experience in Salesforce technology. 21x Certified. Blogger, Speaker, and Instructor. DevSecOps Champion