this keyword in Java

By: Jagan Emailed: 1768 times Printed: 2515 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines the this keyword. this can be used inside any method to refer to the current object. That is, this is always a reference to the object on which the method was invoked. You can use this anywhere a reference to an object of the current class' type is permitted.

To better understand what this refers to, consider the following version of Box( ):

// A redundant use of this.
Box(double w, double h, double d) {
this.width = w;
this.height = h;
this.depth = d;
}

The use of this is redundant, but perfectly correct. Inside Box( ), this will always refer to the invoking
object. While it is redundant in this case, this is useful in other contexts, one of which is explained in the next section.

Instance Variable Hiding

As you know, it is illegal in Java to declare two local variables with the same name inside the same or enclosing scopes. Interestingly, you can have local variables, including formal parameters to methods, which overlap with the names of the class' instance variables. However, when a local variable has the same name as an instance variable, the local variable hides the instance variable. 

This is why width, height, and depth were not used as the names of the parameters to the Box( ) constructor inside the Box class. If they had been, then width would have referred to the formal parameter, hiding the instance variable width. While it is usually easier to simply use different names, there is another way around this situation. Because this lets you refer directly to the object, you can use it to resolve any name space collisions that might occur between instance variables and local variables. For example, here is another version of Box( ), which uses width, height, and depth for parameter names and then uses this to access the instance variables by the same name:

// Use this to resolve name-space collisions.
Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}

A word of caution: The use of this in such a context can sometimes be confusing, and some programmers are careful not to use local variables and formal parameter names that hide instance variables. Of course, other programmers believe the contrary—that it is a good convention to use the same names for clarity, and use this to overcome the instance variable hiding. It is a matter of taste which approach you adopt.

Although this is of no significant value in the examples just shown, it is very useful in certain situations.

This is an extract from the book: Java 2 - The Complete Reference by Herbert Schildt.


Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(23)


1. View Comment

Yes the article is good and useful...!

View Tutorial          By: Regalla Naresh Reddy at 2009-04-12 23:16:24
2. View Comment

I'm sorry but your closing statement...

"this is of no significant value in the examples just shown..."

... is not quite right. "this" is mandatory in your last code snippet (at least with Sun's Java 6). If you leave out the "this" references, you are actually assigning the constructor parameter values to the constructor's local variables - not to the instance variables.

And, to follow best practices, we'd make the arguments final so that, if we forgot the this's, the compiler would call it out for you.


View Tutorial          By: Al Scherer at 2009-09-15 09:33:24
3. View Comment

It's good but not easily understandable....

View Tutorial          By: koshal at 2010-12-19 23:32:05
4. View Comment

the article is very useful...!

View Tutorial          By: pravin salame at 2011-05-20 11:58:28
5. View Comment

Thank u very much, your topic is very clear, to the point & very helpful.

View Tutorial          By: Ahmed Samir at 2011-05-26 23:35:22
6. View Comment

very good description ,clear and simple

View Tutorial          By: swapnil at 2011-06-24 06:33:10
7. View Comment

sir every time we are using this.wedth(for example purpose)why we need this.wedth insted we can use the another variabl like
some wedthe=w; like i didnt understand properly


View Tutorial          By: praveen kumar at 2011-06-28 01:33:44
8. View Comment

Very good description. I was quite confused before reading this. Clears it up a bit.

View Tutorial          By: Donna at 2011-07-31 03:46:05
9. View Comment

i want to knew about byte datatype. why did not byte content byte value like example
byte a=3;
byte b=4;
byte c=a+b;


View Tutorial          By: pankaj kr tiwari at 2011-12-02 04:37:43
10. View Comment

@pankaj because u need to cast it. when u add nums it get converted to integer which is bigger in size so u need to cast it to byte like this

byte c= (byte)a+b;


View Tutorial          By: raziq at 2011-12-18 16:06:09
11. View Comment

THANX :)

View Tutorial          By: Saurabh at 2012-01-02 16:13:06
12. View Comment

it s good ,understanding clearly and with out confusion

View Tutorial          By: vasudeva kumar at 2012-01-06 14:04:30
13. View Comment

we generally use this keyword for referring to the variables..we actually refer the non static method by creating an object to it..but without creating an object can we invoke a constructor in a class using the keyword 'this'...???plz let me know

View Tutorial          By: madhu at 2012-02-07 14:11:57
14. View Comment

""this"" is a implicit keyword or object, created by JVM and supplied to every java program for Two purposes. They are...
1). ''this'' always contains current class object values.
2). ""this "" diffrentiates between formal parameters and data members to avoid ambiguity to JVM.


View Tutorial          By: Gangireddy at 2012-02-15 08:35:18
15. View Comment

this total example is copy paste from the Herbert Schildt's Java book......!!!! :P

View Tutorial          By: Parna at 2012-06-03 05:16:37
16. View Comment

for ex

public class test()
{
int a;
test()
{
this(5);
}
.
.
.

}
will this work??????
thanx in adv.


View Tutorial          By: Anundhara at 2012-08-11 06:54:57
17. View Comment

No it won't work...

View Tutorial          By: Arin at 2012-08-17 09:59:40
18. View Comment

I want to know that what is the main use of the "this" key-word?
Is the this key word is important?
Please give me the Answer..


View Tutorial          By: Krunal Patel at 2012-09-17 08:11:19
19. View Comment

You explained the this Keyword very well.
"this keyword create differences between function parameter and class instance variable with same name so that none of them should overlap each other"


View Tutorial          By: Karan at 2012-12-04 11:27:35
20. View Comment

super explination.

View Tutorial          By: nagarjun reddy at 2013-01-19 13:55:16
21. View Comment

Clear explanation...

View Tutorial          By: Nisha at 2013-01-31 05:10:29
22. View Comment

This explaination is good to understand the basic use of this keyword.But can add more examples to show vast usage of this...

View Tutorial          By: Nisha Thankachan.F at 2013-02-13 05:29:13
23. View Comment

it is very good for best practice of basics........java

View Tutorial          By: sushil ghimire at 2015-03-01 13:27:57

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Jagan
Importing a Certificate for the CA example using keytool in Java
The if-then-else Statement in Java
WHERE Clauses in SQL
The TryCatchFinally Interface in JSP
assert() Function Example program in C
Guidelines for Struts Application Development
Using printf function in C
File Inclusion in C
Using Multiple Message Resource Bundles in Struts
While and For Loops in C
Arrays sample program in C
Controlling Page Navigation in JSF - Static and Dynamic Navigation
Using cout.fill() in C++
Types of Profiles in J2ME
DateField sample program in J2ME

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
InetAddress Example program in Java
Read from a COM port using Java program
Stack example in Java - push(), pop(), empty(), search()
How to use ArrayList in Java
The Basic Structure of a Simple Java program
Using StringTokenizer in Java
FileReader and FileWriter example program in Java
Transient vs Volatile modifiers in Java
Vector example in Java
Method Overriding in Java
Method Overloading (function overloading) in Java
instanceof sample program in Java
append() in Java
Student marks calculation program in Java
Reading from a file and writing to a file using Java program
Most Emailed Articles (in Java)
Text to Speech conversion program in Java
inheritance in Java
How to initialize an Array and how to copy the array
Using Charts in JasperReports
What is Unicode?
Operator Precedence in Java
Of Object, equals (), == and hashCode ()
DateFormat sample program in Java
A Simple whois program in Java
CharArrayReader example program in Java
ByteArrayOutputStream - sample program in Java
Vector example in Java
Arrays example in Java - asList(), binarySearch(), fill(), sort(), equals()
HashSet Sample program in Java
Disadvantages of using Native methods in Java