• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Keyword this

 
J Brewer
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given:

 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this.i refers to the class variable i in this case since this is a reference to an object of type Test.

The i declared inside the method is a local variable.
 
Maureen Augustus
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi J,

Because "int i = 20" is defined within a method, it is a local variable, not an instance variable.

The this keyword references instance variables, like the one you defined with the code "public static int i =99" and then assigned the value 10 within the method.

If you want to display the value "20", your output line would read "System.out.println(i);" to access the local variable instead of the instance variable.
 
J Brewer
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah, so the 'this' keyword refers to the instance or class variable, but not to a local variable. Gotcha.

Thanks!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic