Apex Keywords
Apex provides the keywords final, instanceof, super, this, transient, with sharing and without sharing.
1. final:
The keyword "final" is used to declare a variable that cannot be reassigned once assigned a value.
This variable can be used for declaring a constant value.
Example:
final Integer PI = 3.14;
Double radius = 5.0;
Double area = PI * radius * radius;
System.debug('Area of circle: ' + area);
In the above example, the value of PI is set to 3.14 and cannot be changed because it is declared with the "final" keyword.
2. instanceof:
The keyword "instanceof" checks if an object is an instance of a particular class.
Example:
Account acc = new Account(Name='Test');
if (acc instanceof SObject) {
System.debug('Account is an instance of SObject');
}
In the above example, we check if the Account object is an instance of the SObject class.
3. super:
The keyword "super" allows you to call the overridden method of a parent class.
Example:
public class Vehicle {
public void display() {
System.debug('In Vehicle class');
}
}
public class Car extends Vehicle{
public void display() {
System.debug('In Car class');
super.display();
}
}
In the above example, the Car class extends the Vehicle Class and overrides the "display()" method.
In the "display()" method of the Car class, we call the parent class's "display()" method using the "super" keyword.
4. this:
The keyword "this" refers to the current instance of the class.
Example:
public class Employee {
private String name;
public Employee(String name) {
this.name = name;
}
}
In the above example, we use the "this" keyword to refer to the current instance of the Employee class.
5. transient:
The keyword "transient" is used to indicate that a variable should not be serialized when the object is serialized.
Example:
public class Employee {
transient private String password;
public Employee() {
password = '123456';
}
}
In the above example, the password variable will not be serialized when the Employee object is serialized.
6. with sharing and without sharing:
The keywords "with sharing" and "without sharing" are used to control the level of access to data in a class.
Example:
public with sharing class EmployeeController {
public List<Employee__c> getEmployees() {
List<Employee__c> empList = [SELECT Id, Name FROM Employee__c];
return empList;
}
}
In the above example, we use the "with sharing" keyword to enforce sharing rules on the Employee__c object queried in the getEmployees() method.
This means that the data access will be limited based on the sharing rules defined in the organization.
If we had used "without sharing" instead, no sharing rules would be enforced, and all data would be accessible.
Follow Us