What are Constructors and Methods?
Constructors and methods are fundamental elements in Salesforce development. They play distinct roles in defining and executing the functionality of a class.
Constructor: A constructor is a special type of method that is automatically invoked when an object of a class is created. It is primarily used for initializing the attributes of the object. Constructors have the same name as the class and do not return a value.
Method: A method, also known as a function, is a block of code within a class that performs a specific task when called. Methods can take parameters, perform actions, and return values.
Let's explore the syntax differences between constructors and methods:
Constructor Syntax:
Method Syntax:
Use Cases:
Constructors: Constructors are primarily used for initializing class-level variables and preparing the object for use. They are executed automatically when an object is created, ensuring that the object starts in a valid state.
Methods: Methods are used for implementing specific functionality within a class. They are called explicitly when you need to execute the code they contain. Methods can be called multiple times with different parameters.
Return Types:
Constructors: Constructors do not have a return type, not even "void." They are meant solely for initializing the object.
Methods: Methods can have return types, such as void (for methods that do not return a value) or specific data types like String, Integer, etc., depending on the data they produce.
Naming Conventions:
Constructors: Constructors have the same name as the class and cannot have a different name. For instance, if your class is named MyClass, the constructor will also be named MyClass.
Methods: Methods can have any valid name as long as they adhere to naming conventions and do not conflict with reserved keywords.
Explicit Invocation:
Constructors: Constructors are implicitly invoked when an object of the class is created using the new keyword. You don't need to call them manually.
Methods: Methods are explicitly called using their names and can be invoked multiple times within the class or from other classes.
Let's see some code examples to clarify the differences:
Constructor Example:
Method Example:
In the constructor example, the constructor initializes the name and age attributes when a Student object is created. In the method example, the addNumbers method performs addition and returns the result when called.
0 Comments