Activity Forums Salesforce® Discussions How can I use this keyword in Salesforce? What's the main advantage of using it?

  • Ravi

    Member
    September 7, 2016 at 4:43 pm

    This keyword used to represent the current instance of the class.We use This keyword to differentiate between class instance variable and local variable.

    Example:

    public class ThisKeywordDemo{
        String str = ‘DefaultValue’;
        public ThisKeywordDemo(String str){
            System.debug(‘–local Value–‘+str);
            System.debug(‘–Current Instance Value–‘+this.str)
            this.str = str;
        }
    }

    The above example has One Instance Variable & One Local Variable or Method parameter with same name.

    str = Refers parameter value.
    this.str = Refers the current instance variable value.

    To execute this class go to Developer Console, paste the below line then click execute.

    ThisKeywordDemo thisExample = new ThisKeywordDemo('test This Keyword');

    • This reply was modified 8 years, 2 months ago by  Ravi.
  • Avnish Yadav

    Member
    September 30, 2018 at 4:13 am

    Hello,

    As per your question on advantage of using this keyword over passing the object itself is thisis a final variable in Java whereas the object when passed may or may not be final.

    Thanks.

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos