Apex Class
public class ApexClass{
Integer x;
Integer y;
public void sum(){
this.x=12;
this.y=15;
Integer sum=this.x+this.y;
System.debug('The sum of '+this.x+ ' and '+this.y+' is '+sum);
}
}
Apex Code
ApexClass obj = new ApexClass();
obj.sum();
Execution Log
DEBUG|The sum of 12 and 15 is 27
Considerations
This cannot be referenced in a static context
More Examples
public class Person {
private String name;
private Integer age;
public Person(String name, Integer age) {
this.name = name; // "this" refers to the current instance of the Person class
this.age = age;
}
public void printDetails() {
System.debug('Name: ' + this.name); // "this" is optional here, but it can make the code more readable
System.debug('Age: ' + age); // "this" is not needed here, since there is no local variable named "age"
}
}