Notes
In Apex, a constructor is a special method within a class that is used for initializing the object's state. Constructors are called when an object of a class is created. They allow you to perform any necessary setup or initialization logic for the object.
Here are some key points about constructors in Apex:
Default Constructor: If you don't define a constructor, Apex provides a default constructor with no parameters and no logic.
public class MyClass {
public String name;
public MyClass() {
name = 'John Smith';
System.debug(name);
}
}
Execute this code in Anonymous Window
MyClass objA = new MyClass();
Output: John Smith
Parameterized Constructor: You can create constructors with parameters to initialize the object with specific values.
public class MyClass {
public String name;
public MyClass(String n) {
name = n;
System.debug(name);
}
}
Execute this code in Anonymous Window
MyClass objA = new MyClass('Emma Whatson');
Output: Emma Whatson
Video
Video does not exists.