The this Keyword
By: aathishankaran
The this Keyword
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 program
class Box {
double width;
double height;
double depth;
Box ( double w, double h, double) {
width = w;
height = h;
depth = d;
}
double volume(){
return width * height * depth;
}
}
class BoxDemo {
public static void main (string args[]) {
Box mybox1 = new Box (10,20,15);
double vol;
vol = mybox2.volume();
System.out.println("Volume is" + vol);
}
}
In this program we can use the below coding for defining the values for the data member by using this keyword
Box ( double w, double h, double) {
this.width = w;
this.height = h;
this.depth = d;
}
This coding for Box() also operates exactly like the pervious Box() code. The use of this is redundant, but perfectly correct. Inside Box(), this will always refer to the invoking object. Here this refers the current variable. While it is redundant in this case, this is useful in other contexts, in some particular situations.
Archived Comments
1. good. very nice.
View Tutorial By: anuprassana at 2007-03-03 04:22:42
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
Java program to get location meta data from an image
Program using concept of byte long short and int in java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Count number of vowels, consonants and digits in a String in Java
Student marks calculation program in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program