Apex is a strongly typed, object-oriented programming language that is designed to handle large amounts of data. Constructor in Apex Programming is a code that is called when an object is created from the class.
Properties of Constructor
- Method name should be the same as the Class name.
- Access specifiers should be defined as public.
- This method is called automatically when the objects are created.
Constructor Definition Syntax
public class New
\\ the no argument Constructor
Types of Constructor
- Default Constructor/Non-parameterized Constructor.
- Copy Constructor
- Parameterized Constructor.
The default constructor doesn’t contain any parameters. It is used to initialize every object with the same data.
If an Apex Class does not have any constructor, then Apex Compiler creates a dummy constructor with the name similar to the class name when an object is created for the class.
public class Test
Test t = new Test();
A parameterized constructor contains one or more parameters(the list of arguments). It is used to initialize each object with different data.
The copy constructor is a constructor that creates an object by initializing it with an object of the same class that has been created previously.
Uses of copy constructor:
- Initialize one object from another of the same type.
- Copy an object to pass it as an argument to a function.
- Copy an object to return it from a function.
Constructor Chaining is the process of calling one constructor from another constructor within the same class.
The main advantage of Constructor Chaining is that you can pass parameters with a bunch of different constructors, but the initialization should be done at a single location. This enables you to maintain your initialization from a single location while providing multiple constructors to the user.
Constructor Chaining can be done in two ways:
- Within the same class: It can be done using this() keyword for constructors in the same class.
- From base class: Using super() keyword to call a constructor from the base class.
Constructor Overloading is a concept of having more than one constructor with different parameters list, in such a way so that each constructor performs a different task.
// Constructor code
// Constructor code
other Variables & Functions
A constructor in Apex programming is a special method that is used to create and initialize an object within a class.
If you want to know more about how to get started with Constructor, contact our Salesforce Certified developers now.
At Cloud Analogy, our certified developers will assist you to get the advantage of different types of constructors and will help you understand the coding basics of Apex programming.