This week's giveaway is in the Spring forum.
We're giving away four copies of Learn Spring Security (video course) and have Eugen Paraschiv on-line!
See this thread for details.
Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Confuse about "this" keyword

 
Lucky Lam
Greenhorn
Posts: 10
Android Java Netbeans IDE
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I'm really confused about "this" keyword in this situation...Could you please explain it in details? It would be appreciate!
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15203
36
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this refers to the current object (the object that the method that is executing, was called on).

In line 18, you create a new Apple object which is passed to the eat method of class Person.
In line 3, you call getPeeled on that Apple object.
In line 14, the Apple object calls Peeler.peel, passing itself to that method.
 
Maneesh Godbole
Saloon Keeper
Posts: 11021
12
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The "this" keyword indicates the current instance. In your code, it is the Apple instance current with the Peeler which the Person is going to eat

To simplify


this.age on line 4 refers to the age defined on line 2. So essentially you say assign the value of age on line 3 to the age defined on line 2.

More details here http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html

 
James Boswell
Bartender
Posts: 1051
5
Chrome Eclipse IDE Hibernate
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The 'this' keyword is used to refer to the current instance - in your case, an instance of the class Apple.

Using the this Keyword
 
Lucky Lam
Greenhorn
Posts: 10
Android Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So instead of using "this", is there other way to perform? Thanks so much!
 
James Boswell
Bartender
Posts: 1051
5
Chrome Eclipse IDE Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, the peel method in the Peeler class takes an Apple instance as an argument. So nothing stops you from passing in a different Apple instance.

However, the Apple class is delegating the action of peeling to the Peeler class (in it's gelPeeled method) so there is no substitute for using the this keyword here.
 
Volodymyr Lysenko
Ranch Hand
Posts: 511
1
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This was already replied in any possible way .
My reply is:
Keyword this refers to instance of enclosing class.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic