• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

this

 
neelam samnani
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I got in trouble with "this " , Why this program is not giving compilation error, that "this " is undefined variable.

public class Test {
static int total = 10;
public static void main (String args []) {
new Test();
}
public void Test () {
System.out.println("In test");
System.out.println(this);
int temp = this.total;
if (temp > 5) {
System.out.println(temp);
}}
}
Pls. help me.
 
Manfred Leonhardt
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi neelam,
Every non-static method inherently has a 'this' variable. Since your Test() method is non-static 'this' is defined.
Regards,
Manfred
 
Philosopher
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeah actually 'this' variable points to the current object for which the method is being executed. For example if you create an object and call a non-static method. 'this' variable will be passed to the method by default and you will be able to use it to access the attributes/operations of the current object for which the method is being executed
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic