A thorough understanding of this pointer in Java

Source: Internet
Author: User

Every time I see the this pointer in Java, I can't figure it out. I have read many people's explanations on the Internet, but I still don't know what the this pointer is. Today's log shows you who this is. (Content from: http://www.mathcs.emory.edu /~ Cheung/Courses/170.2010/Syllabus/03/implicit-param.html)

Abstract: The this pointer is an Implicit Parameter. What is Implicit Parameter.

Implicit Parameter

 

  • Parameters toInstanceMethod

     

    • Recall that a parameterIs a value that is given to a method as input-see: click here

       

      • Methods can have one or moreParameters

         

      • You can pass one or more inputs into a method by specifying the value as parameters when you invoke the method.

       

    • We have learned that instance methodsHave two different kindsOf parameters:

       

      • ExplicitParameterThat is passed by specifying the parameterIn the parenthesis of a method call.

         

      • ImplicitParameterThat is passed by specifying an object variable (object reference)Before the name of a method.

     

     

  • ExplicitParameter

     

    • Review:

       

       

      Parameters between the brackets/parenthesisOf the method call are calledExplicitParameters

       

       

    • Examples:The values in are explicit parameters

       

          harrysChecking.deposit();           harrysChecking.withdraw();           box.translate(, );    double x = 4.0, y = 6.0;    box.translate(, );

       

      • NOTE: these statement must be contained in some method, and most likely, they will be in different methods (because their actions are kinda "unrelated ". I have omitted the method for brew.just want to show you how to identify explicit parameters

       

     

     

  • AccessingExplicitParameter variable inside the method

     

    • AccessingExplicitParameter variable inside a method is very simple:

       

      To useExplicitParameter variable inside a method, you simply refer the parameter variable by its name

       

    • Example:

       

           public void deposit(double )         {        balance = balance + ;         }

      (Because this is so trivial, I did not dwell on it when we discuss the implementation of the methods.

      I dwell on it now because I will show you how to accessImplicitParameter variable next .)

     

     

  • ImplicitParameter

     

    • Review:

       

       

      Object variable before the method nameIn the method call are calledImplicitParameters

       

       

    • The objectOn which you invoke a method is also as a parameterIn the method call, because if you use a different object in the method call, the operation is performed med on a different object (I. e., the behavior of the method is modified ):

       

         .deposit(500);       .deposit(500);

      The first call updatesBalanceInstance variable inHarrysChecking, While the second call updatesBalanceInstance variable inMomsSaving

     

     

  • AccessingImplicitParameter inside the method

     

    • There is exactly ONE ImplicitParameter variable in every method.

       

    • Java has assigned a special name (a keyword)To identify thisImplicitParameter variable

       

    • TheKeywordThat Java (and C ++) uses to refer toImplicitParameter variable is calledThis

      It must be written with all lower case letters

       

       

    • The obvious question that you will be asking is:

      Question:

       

      • What value doesImplicitParameter variableThisContain ???

       

    • You can figure the answer to this question by using analogy...

      Consider the following two pieces of program fragments:

       

       public void deposit(double )   {    balance = balance + ; }
       (1) harrysChecking.deposit(700);   (2) momsSaving.deposit(500);  

      Question:

      What is the value of (ExplicitParameter variable) amount In the case (1 )?

       

      Amount

      Question:

      And what is the value of (ExplicitParameter variable) amount In the case (2 )?

       

      Amount

       

       

    • OK, it's time to apply the analogy:

      Question:

      What is the value of (ImplicitParameter variable) this In the case (1 )?

       

      This

      Question:

      And what is the value of (ImplicitParameter variable) this In the case (2 )?

       

      This

      Here is a pictorial representation on what's going on inside the computer whenMomsSaving. deposit (500)Is called:

       

       

       

       

    • As you know, object variables suchHarrysCheckingAndMomsSavingAre used to locate the instance variablesOf an object-see: click here

      Since the object variable (HarrysCheckingIn case (1) andMomsSavingIn case (2) is passed toImplicitParameter variable ThisIn the method call, the method can useThisTo obtain the correctInstance variables!!!

      (That's how the magic works ....)

       

    • Important Fact:

       

      TheImplicitParameter variableThisIs an object reference variableAnd is used to locate the instance variables of the object

       

       

    • It remains to show youHowTheImplicitParameter variable ThisIs used...

      Example:

       public void deposit(double amount) {     =  + amount; }
       public void deposit(double amount) {    . = . + amount; }

       

      • Notice that the variableBalanceIs an instance variable in the object that is being referenced byImplicitParameter variable This

         

      • Java assumes that a variable name that does not any a name ofParameterVariable orLocalVariableMust refer to an instance variable

        That's why you don't need to writeThisBefore the variableBalance

     

  • A case that necessitate the useThis

     

    • It isRareThat you need to useImplicitParameter variable This

       

    • Here is one case where it is necessary to useThis, But it is only so, because of a very bad choice of nomenclature:

       

      Is the sameAs the name of the instance variable

       

    • Example where you need to useThisIn the method:
       public void deposit(double amount) {     =  + amount; }
       public void deposit(double ) {     =  + ; }

       

    • TheDeposit ()On the right will not work properly ....

      You can fix this by usingThis:

       

       public void deposit(double ) {     =  + ;   }

       

  • DEMO Program:(BankAccount classThis)

     

    • BankAccount. java file: click here
    • BankAccountTester. java file: click here

       

    • Compile:Javac BankAccountTester. java
    • Run:Java BankAccountTester

       

    • Now editBankAccount. javaAnd removeThis., Compile and run the program again...

      The methodDeposit ()Can no longer increase the balance inBankAccountObject...

       

    • Question: why not ???

      The nameBalanceMatches the name ofParameter variableAnd thus, the nameBalanceRefers toParameter variableAndNotToInstance variable

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.