aspose file tools*
The moose likes Java in General and the fly likes Confuse about Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Confuse about "this" keyword" Watch "Confuse about "this" keyword" New topic
Author

Confuse about "this" keyword

Lucky Lam
Greenhorn

Joined: Sep 03, 2013
Posts: 10


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

Joined: Aug 16, 2005
Posts: 14431
    
  23

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.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10535
    
    9

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


[How to ask questions] [Donate a pint, save a life!] [Onff-turn it on!]
James Boswell
Bartender

Joined: Nov 09, 2011
Posts: 1031
    
    5

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

Joined: Sep 03, 2013
Posts: 10

So instead of using "this", is there other way to perform? Thanks so much!
James Boswell
Bartender

Joined: Nov 09, 2011
Posts: 1031
    
    5

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 Levytskyi
Ranch Hand

Joined: Mar 29, 2012
Posts: 505
    
    1

This was already replied in any possible way .
My reply is:
Keyword this refers to instance of enclosing class.


True person is moral, false is right!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Confuse about "this" keyword