I have a question in 'this' keyword of APEX. The following is a simple BATCH class it calls a BatchProcess class.

global class Household_BATCH implements Database.Batchable<SObject>, Database.Stateful {

    global Id batchJobId;
    private Process_Service ProcessService;

    global Household_BATCH() {
        this.ProcessService = new Process_Service();

    global Database.QueryLocator start(Database.BatchableContext bc) {

        String query = 'SELECT Id, AccountId, Account.RecordType.Name FROM Contact WHERE Account.RecordType.Name = \'Household\' AND Id IN (SELECT Contact__c FROM Request__c WHERE Status__c = \'Processing\')';
        return Database.getQueryLocator(query);

    global void execute(Database.BatchableContext bc, List<Contact> contacts) {
        try {
            this.batchJobId = bc.getJobId();
         this.ProcessService.updateHouseholdAccountsContactsAccount(contacts, this.batchJobId);
        } catch (Exception e) {


    global void finish(Database.BatchableContext bc) {


In the above BATCH I defined the batchJobId, ProcessService as global variable and assign value or access this value inside methods like in the class. Here my question is, Is it necessary to put 'this' keyword when you access the global variable? I am really confused here because everything is worked as I expect even I used the 'this' keyword or not.


2 Answers 2

  1. Use of the "this." prefix in a variable name has no negative impact other than perhaps cluttering your code unnecessarily
  2. It is needed when there is a local variable (e.g. method parameter) with the same name as the attribute (class member variable) and you want to access the attribute. A local variable "shadows" an attribute with the same name, so you must use "this." prefix to access the attribute, otherwise the local variable is accessed.
  3. As a bonus point: don't use "global" modifiers for your batch implementation class and methods unless you want to expose this batch for use outside your package (if you are packaging this code). If you have no package and you are not making the batch accessible by code inside a package then you can just make it "public" all the way.

This is used to determine that you are using a global Variable. In some cases, you could not have issue. In the case below, you could face.

public class TestThisVariable {

    public string testText;

    public void setText(string testText) {
        testText = 'Hello!';


After run the setText, what is the value of public testText?

It will be null.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .