Basic overview of Apex classes, variables, constructors, and methods in Salesforce
Apex is a strongly-typed, object-oriented programming language that allows developers to write custom business logic and perform complex operations on Salesforce data. Let's go through the basic components of an Apex class, including variables, constructors, and methods.
Apex Class:
An Apex class is a blueprint for creating objects in Salesforce. It defines the structure and behavior of objects by encapsulating data and methods.
Here's a simple example of an Apex class:
public class MyClass {// Variables
public String name;
public Integer age;
// Constructor
public MyClass(String n, Integer a) {
name = n;
age = a;
}
// Method
public void displayInfo() {
System.debug('Name: ' + name);
System.debug('Age: ' + age);
}
}
Variables:
Variables are containers used to store data within an Apex class. There are different types of variables in Apex, including instance variables, local variables, and static variables. In the example name and age are instance variables (also known as member variables) because they are declared at the class level and belong to individual instances of the class.
Constructor:
A constructor is a special method used to initialize objects when they are created. Constructors have the same name as the class and do not have a return type. In the example, MyClass(String n, Integer a) is a constructor that initializes the name and age variables when a MyClass object is created.
Methods:
Methods are functions defined within a class that perform specific actions or calculations. They encapsulate behavior and can manipulate data within the class. In the example, displayInfo() is a method that displays the name and age of the object.
Usage Example:
You can create an instance of the MyClass class, set its variables using the constructor, and call its methods as follows:
MyClass obj = new MyClass('John', 30);
Comments
Post a Comment