Results 1 to 4 of 4
Thread: Quick 'this' question
- 05-08-2012, 06:42 AM #1
Senior Member
- Join Date
- Jan 2012
- Posts
- 142
- Rep Power
- 0
Quick 'this' question
public class testers{
private int x =0;
public testers(int x ){
this.x = this.x +1;
x = this.x + 2;
}
public static void main(String[] args){
testers app = new testers(5);
System.out.println(app.x);
}
}
I was just wondering why this always prints 1. I'm confused with the this.x = this.x + 1 line, what does it mean?
Also in the main method what does app.x mean?
Thanks very much for your time.
- 05-08-2012, 07:05 AM #2
Senior Member
- Join Date
- Oct 2010
- Location
- Germany
- Posts
- 780
- Rep Power
- 4
Re: Quick 'this' question
The parameter int x of your testers method covers the declared variable private int x. So if you want to use the class/object x variable, you have to use the this keyword to distinguish!
The x variable in the testers method is only visible in the body of the method and app.x shows to the private int x.
This is only 1, because this.x = this.x +1 -> 0 + 1 = 1
If you would add a System.out.println(x) in the testers method (at the end) it would print 3 -> 1(the "global x") + 2 = the local x = 3
- 05-08-2012, 07:14 AM #3
Senior Member
- Join Date
- Jan 2012
- Posts
- 142
- Rep Power
- 0
- 05-08-2012, 07:21 AM #4
Senior Member
- Join Date
- Oct 2010
- Location
- Germany
- Posts
- 780
- Rep Power
- 4
Similar Threads
-
quick question
By biggerthanblue in forum New To JavaReplies: 2Last Post: 04-10-2011, 04:33 AM -
Quick Question...
By FatalSylence in forum New To JavaReplies: 4Last Post: 10-15-2010, 02:38 PM -
Quick question
By sAntA199 in forum New To JavaReplies: 2Last Post: 12-09-2009, 03:01 AM -
One last quick question
By jigglywiggly in forum New To JavaReplies: 7Last Post: 01-26-2009, 08:53 AM -
Quick Question
By Graeme in forum New To JavaReplies: 4Last Post: 01-08-2009, 08:01 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks