when to use the `this` keyword when writing extension classes

I’m looking through some code, and I don’t quite follow the use of the this keyword in an extension class. It the code shown below, when the objected is instantiated the this kw is used, but when it’s being modified or referenced (say for comparison) this is not used.

What’s going on here? When do you use this KW when dealing with extension classes?

public class myControllerExtension {

    private final Account acct;

    // The extension constructor initializes the private member
    // variable acct by using the getRecord method from the standard
    // controller.
    public myControllerExtension(ApexPages.StandardController stdController) {
        this.acct = (Account)stdController.getRecord();
        acct.OwnerId = UserInfo.getOwnerId();
    }

Answer

The keyword this is used to explicitly call out that the code is referencing a member of the object. In some languages it can be left off (and is therefore implicitly implied) and this can be a matter of stylistic preference. Using it indicates that you explicitly want the member belonging to this instance (as opposed to a static, base, or super instance related to your object.)

Most often this is used to differentiate between constructor variables and member variables of the same name (or in other cases where it’s ambiguous which variable you’re referring to). For example

public class TriggerHelper {
  private List<Opportunity> opptys;

  public TriggerHelper(List<Opportunity> opptys) {
    this.opptys = opptys;
  }
}

For further Reference: Salesforce documentation on the this keyword.

Attribution
Source : Link , Question Author : PartOfTheOhana , Answer Author : Ralph Callaway

Leave a Comment