Results 1 to 16 of 16
Like Tree2Likes
  • 1 Post By Tolls
  • 1 Post By quad64bit

Thread: The this keyword

  1. #1
    Army is offline Senior Member
    Join Date
    Jan 2012
    Posts
    147
    Rep Power
    0

    Default The this keyword

    I don't really understand the this keyword. I have looked at javaDocs and I understand nothing. Can someone put it in English and not all this crazy mumbo-jumbo-lingo. I just need like a metaphor or something to help me out.

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,224
    Rep Power
    20

    Default Re: The this keyword

    It's the object you're in.
    quad64bit likes this.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  3. #3
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,773
    Blog Entries
    7
    Rep Power
    21

    Default Re: The this keyword

    I like the way SmallTalk handles those problems: something (an object) talks to another object. What the object has to say is the method. The destination of the method can be the object itself. So the first object talks to itself; SmallTalk manages this (sic) with the 'self' keyword. C++ and Java (and some more languages) use the word 'this' instead.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  4. #4
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default Re: The this keyword

    What these guys said.

    It's easy to forget that at runtime, the code you are looking at gets instantiated into an object, and that might might have many objects of the same type created from the same blueprint (the code). When you say 'this' in one of those objects, it specifically means the instance executing the code in question, not another instance. Here is a simple example:

    Java Code:
    public class Person{
        String name;
    
        public Person(String name){
             this.name = name;
        }
    }
    In this example, the keyword 'this' allows us to distinguish between the variable called 'name' that belongs to the Person class, and the variable called name that is a parameter in the Person constructor. this.name = name; means in english: "Take the variable called name belonging to me (this instance of person) and assign it the value of the parameter called name that was supplied to me in my constructor".

    Another example might be something like this:
    Java Code:
    public class Alpha{
        public int value;
    
        public Alpha(int initialValue){
            value = initialValue; // I didn't use this here because the names are distinct, but I could have if I wanted to!
        }
    
        public void alphaPrinter(Alpha alpha){
            System.out.println(alpha.value);
        }
    
        public void test(){
            alphaPrinter(this); //prints the value of whatever 'this' alpha contains
            alphaPrinter(new Alpha(3)); //prints a 3
        }
    }
    
    //...
    
    public class Main{
        public static void main(String[] args){
            Alpha a = new Alpha(25);
            a.test();   //this will print a 25, then a 3 because inside 'a', it's own value is printed first, and then a new alpha is created and printed.
        }
    }

  5. #5
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,458
    Rep Power
    20

    Default Re: The this keyword

    Quote Originally Posted by JosAH View Post
    SmallTalk manages this (sic) with the 'self' keyword. C++ and Java (and some more languages) use the word 'this' instead.
    Visua FoxPro uses THIS. Also THISFORM and THISFORMSET.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  6. #6
    Army is offline Senior Member
    Join Date
    Jan 2012
    Posts
    147
    Rep Power
    0

    Default Re: The this keyword

    I still don't understand...

    Are you saying it's like a parent gives a kid a name but then that kid has another kid and that kid gives his kid his name so then they all share names?

  7. #7
    Chri is offline Member
    Join Date
    Aug 2012
    Location
    Switzerland
    Posts
    49
    Rep Power
    0

    Default Re: The this keyword

    Java Code:
    int x;
    
    public setX(int x){
    this.x = x;
    }
    it means that THIS x, the one in the parenthesis of the method would be equal to the variable x, so if in another method I write

    setX(9);

    it will say: this x, or the int in the parenthesis, the argument, is equal to the variable x, so now x=9

  8. #8
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,773
    Blog Entries
    7
    Rep Power
    21

    Default Re: The this keyword

    Quote Originally Posted by Army View Post
    I still don't understand...

    Are you saying it's like a parent gives a kid a name but then that kid has another kid and that kid gives his kid his name so then they all share names?
    No, simply think of 'this' as 'I' or 'my' or 'mine'; e.g. 'this.name= name' reads as 'my name gets the value of name' and 'this.doSomething()' reads as 'I doSomething()'. etc. etc. It's as if each object has a mind of its own and it knows about itself by the keyword 'this'. So for each object 'this' means something else ...

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  9. #9
    Army is offline Senior Member
    Join Date
    Jan 2012
    Posts
    147
    Rep Power
    0

    Default Re: The this keyword

    See and that is where I get confused. Doesn't the object "already know" something about itself. I get confused because I think this is pretty useless.

  10. #10
    Chri is offline Member
    Join Date
    Aug 2012
    Location
    Switzerland
    Posts
    49
    Rep Power
    0

    Default Re: The this keyword

    simply, this refers to the object that is in the arguments of the method, so you can use the value of that and assign it to a variable for example

  11. #11
    Potato is offline Member
    Join Date
    Dec 2011
    Posts
    25
    Rep Power
    0

    Default Re: The this keyword

    Quote Originally Posted by Army View Post
    See and that is where I get confused. Doesn't the object "already know" something about itself. I get confused because I think this is pretty useless.
    What about a situation like this?

    Java Code:
    public class Example {
    
    	public static void main(String[] args) {
    		Example example = new Example();
    		example.test(10);
    	}
    
    	public int a = 5;
    
    	public void test(int a) {
    		// What is the value of a? 10 or 5??
    	}
    }
    You have a variable in the class named 'a' and an argument in the method test named 'a'?

    How do you say that you want to access the class variable 'a'?

    The solution is to use this.a

    Java Code:
    public class Example {
    
    	public static void main(String[] args) {
    		Example example = new Example();
    		example.test(10);
    	}
    
    	public int a = 5;
    
    	public void test(int a) {
    		// What is the value of a? 10 or 5??
    
    		System.out.println("'this.a' is equal to " + this.a + "!");
    		System.out.println("However, 'a' is equal to " + a + ".");
    	}
    }
    Look at the output of that program

  12. #12
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default Re: The this keyword

    I think this is pretty useless.
    Only because you don't understand it. It is a very common idiom to have a class that implements an interface use a reference to itself. An example is an action listener. If you had something like

    Java Code:
    public class Window extends JFrame implements MouseMotionListener{
        public static void main(String[] args){
            new Window();
        }
    
        public Window(){
            //Without 'this', how would I do this? This is a pretty common technique. 
            addMouseMotionListener(this);
        }
    
        public void mouseDragged(MouseEvent e){
            //do something on a mouse click'n'drag
        }
    
        public void mouseMoved(MouseEvent e){
            //Do something on a mouse move
        }
    }
    Another example would be something like this:

    Java Code:
    public class Alpha{
        private Alpha parent;
     
        public void setParent(Alpha parent){
            this.parent = parent;
        }
    
        //In this case, the current alpha instance is the parent. It creates inside of it
        //another instance of alpha called child. To tell the child who it's parent is, 
        //we pass it a reference to the current object. Can you think of a way to
        //do this without 'this'?
        public void introduce(Alpha child){
            child.setParent(this);
        }
    
        public static void main(String[] args){
            Alpha parent = new Alpha();
            Alpha child = new Alpha();
            parent.introduce(child);
        }
    }
    Last edited by quad64bit; 12-14-2012 at 05:05 AM.

  13. #13
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default Re: The this keyword

    P.S. 'this' is used a LOT in data structures like linked lists, trees, maps, graphs, etc...

  14. #14
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,458
    Rep Power
    20

    Default Re: The this keyword

    Quote Originally Posted by quad64bit View Post
    Another example would be something like this:

    Java Code:
    public class Alpha{
    	private Alpha parent;
    
    	public void setParent(Alpha parent){
    		this.parent = parent;
    	}
    
    	public static void main(String[] args){
    		Alpha child = new Alpha();
    		//In this case, the current alpha instance is the parent. It creates inside of it
    		//another instance of alpha called child. To tell the child who it's parent is, 
    		//we pass it a reference to the current object. Can you think of a way to
    		//do this without 'this'?
    		child.setParent(this);
    	}
    }
    You can't reference 'this' from a static context.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  15. #15
    wsaryada is offline Senior Member
    Join Date
    Jun 2007
    Location
    Bali, Indonesia
    Posts
    760
    Rep Power
    8

    Default Re: The this keyword

    Quote Originally Posted by Army View Post
    See and that is where I get confused. Doesn't the object "already know" something about itself. I get confused because I think this is pretty useless.
    Yes, the object know it self. But think again in this example:

    Java Code:
    public class User {
        private String name;
    
        public User(String name) {
            this.name = name;
        }
    }
    See how we use this keyword in the constructor. In the constructor we have an argument named name. To assign name argument to the User's name field you have to use the this keyword. Because if you simply use name = name; then it will not get you anywhere. Because the name argument is only available in the constructor. That's why when you want to refer to User's name field you have to use this.name.

    If the name of your class field in not the same with the constructor argument then you can simply use the field name without the this keyword. For example:

    Java Code:
    public class User {
        private String name;
    
        public User(String username) {
            name = username;
        }
    }
    I hope this example using the constructor can help you to understand it better.

  16. #16
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default Re: The this keyword

    You can't reference 'this' from a static context.
    Ooops, sorry about that everyone. In my haste to make a quick example, I made a dumb mistake. I'll modify my example for future readers!
    DarrylBurke likes this.

Similar Threads

  1. Using 'this' keyword in constructor
    By kudwn in forum New To Java
    Replies: 2
    Last Post: 10-11-2010, 01:12 PM
  2. Using 'this' keyword in constructor
    By kudwn in forum New To Java
    Replies: 5
    Last Post: 10-11-2010, 10:47 AM
  3. Use of keyword instanceof
    By darek9576 in forum New To Java
    Replies: 3
    Last Post: 03-14-2010, 11:35 PM
  4. this keyword
    By coltragon in forum New To Java
    Replies: 10
    Last Post: 03-01-2010, 10:20 AM
  5. Use of this keyword
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 11-18-2007, 08:32 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •