每次看到Java中的this指针,总摸不着头绪。在网上看了很多人的讲解,还是不知道this指针到底是什么东西,今天的的这篇日志可以让你看清this到底是谁。(内容摘自:http://www.mathcs.emory.edu/~cheung/Courses/170./Syllabus/03/implicit-param.html)
抽象的讲,this指针就是一个Implicit Parameter,那到底什么是Implicit Parameter,请看下文详解。
Implicit Parameter
Parameters to aninstancemethod
Recall that aparameteris a value that is given to a method as input - see:click here
Methods can haveone 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 thatinstance methodshavetwo different kindsof parameters:
Explicitparameterthat is passed by specifying theparameterin the parenthesis of a method call.
Implicitparameterthat is passed by specifying anobject variable (object reference)before the name of a method.
Explicitparameter
Review:
Theparameters between the brackets/parenthesisof the method call are calledexplicitparameters
Examples:the values inredareexplicit parameters
harrysChecking.deposit(500);
harrysChecking.withdraw(amount);
box.translate(10, 20);
double x = 4.0, y = 6.0;
box.translate(x, y);
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 brevity - just want to show you how to identifyexplicit parameters
Accessing anexplicitparameter variable inside the method
Accessing anexplicitparameter variable inside a method is very simple:
To use anexplicitparameter variable inside a method, you simply refer the parameter variable by its name
Example:
public void deposit(double amount)
{
balance = balance + amount;
}
(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 access theimplicitparameter variable next.)
Implicitparameter
Review:
Theobject variable before the method namein the method call are calledimplicitparameters
Theobjecton which you invoke a method is also as aparameterin the method call, because if you use a different object in the method call, the operation is performed on a different object (i.e., the behavior of the method is modified):
harrysChecking.deposit(500);
momsSaving.deposit(500);
The first call updates thebalanceinstance variable inharrysChecking, while the second call updates thebalanceinstance variable inmomsSaving
Accessing theImplicitparameter inside the method
There isexactly ONEimplicitparameter variable in every method.
Java has assigned aspecial name (a keyword)to identify thisimplicitparameter variable
Thekeywordthat Java (and C++) uses to refer to theimplicitparameter variable is calledthis
It must be written with alllower case letters
The obvious question that you will be asking is:
Question:
What value does theimplicitparameter variablethiscontain ???
You can figure the answer to this question by using analogy...
Consider the following two pieces of program fragments:
public void deposit(double amount)
{
balance = balance + amount;
}
(1) harrysChecking.deposit(700);
(2) momsSaving.deposit(500);
Question:
What is the value of the(explicitparameter variable)amountin the case (1) ?
amount= 700
Question:
And what is the value of the(explicitparameter variable)amountin the case (2) ?
amount= 500
OK, it's time to apply the analogy:
Question:
What is the value of the(implicitparameter variable)thisin the case (1) ?
this= harrysChecking !!!
Question:
And what is the value of the(implicitparameter variable)thisin the case (2) ?
this= momsSaving !!!
Here is a pictorial representation on what's going on inside the computer whenmomsSaving.deposit(500)is called:
As you know, object variables such asharrysCheckingandmomsSavingare used to locate theinstance variablesof an object - see:click here
Since the object variable (harrysCheckingin case (1) andmomsSavingin case (2)) is passed to theimplicitparameter variablethisin the method call, the method can usethisto obtain thecorrectinstance variables!!!
(That's how the magic works....)
Important Fact:
Theimplicitparameter variablethisis anobject reference variableand is used to locate the instance variables of the object
It remains to show youhowtheimplicitparameter variablethisis used...
Example:
public void deposit(double amount)
{
balance = balance + amount;
}
public void deposit(double amount)
{
this.balance = this.balance + amount;
}
Notice that the variablebalanceis an instance variable in the object that is being referenced by theimplicitparameter variablethis
Java assumes that a variable name thatdoes not any a name of aparametervariable or alocalvariablemust refer toan instance variable
That's why you don't need to writethisbefore the variablebalance
A case that necessitate the use ofthis
It israrethat you need to use theimplicitparameter variablethis
Here is one case where it is necessary to usethis, but it is only so, because of a very bad choice of nomenclature:
the name of (one of the) parameter variableis the sameas the name of the instance variable
Example where you need to usethisin the method:
public void deposit(double amount)
{
balance = balance + amount;
}
public void deposit(double balance)
{
balance = balance + balance;
}
Thedeposit()on the right will not work properly....
You can fix this by usingthis:
public void deposit(double balance)
{
this.balance = this.balance + balance;
}
DEMO Program:(BankAccount class withthis)
BankAccount.java file:click here
BankAccountTester.java file:click here
Compile with: javac BankAccountTester.java
Run with: java BankAccountTester
Now editBankAccount.javaand remove thethis., compile and run the program again...
The methoddeposit()can no longer increase the balance in aBankAccountobject...
Question: WHY NOT ???
The namebalancematches the name of aparameter variableand thus, the namebalancerefers to theparameter variableandnotto theinstance variable