Results 1 to 4 of 4
  1. #1
    Gousia is offline Member
    Join Date
    Feb 2011
    Posts
    38
    Rep Power
    0

    Default How to use "this" Keyword

    Hi,

    I am just learning Java.Please let me know what are the advantages of using this Keyword as i found that without using the keyword still we can meet our requirement:):)

  2. #2
    goldest's Avatar
    goldest is offline Senior Member
    Join Date
    Oct 2009
    Location
    Pune, India
    Posts
    469
    Rep Power
    5

    Wink

    Read this: Using this keyword

    Goldest
    Java Is A Funny Language... Really!
    Click on * and add to member reputation, if you find their advices/solutions effective.

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

    Default

    The 'this' keyword is useful in three or four primary cases:
    1) You can avoid having to come up with new parameter names for getters/setters:
    Java Code:
    public class SomeClass{
        String name;
        int age;
        boolean male;
    
        public void setValues(String name, int age, boolean male){
            this.name = name;
            this.age = age;
            this.male = male;
        }
    }
    2) You can pass a reference to the current class to another class/method
    Java Code:
    public class SomeClass{
        private SomeOtherClass soc;
        public SomeClass(){
            soc = new SomeOtherClass(this);  //case #2
        }
    }
    
    public class SomeOtherClass{
        private SomeClass sc;
        public SomeOtherClass(SomeClass sc){
            this.sc = sc;  //case #1
        }
    }
    3) You can use it in a [sub]class to show that a method belongs to the current class
    4) You can use it to invoke a pop-up in most IDEs which gives a listing of all methods in the current class (very useful for inheritance, where the current class inherits many many invisible/unknown methods from superclasses).

  4. #4
    break is offline Member
    Join Date
    Mar 2011
    Posts
    3
    Rep Power
    0

    Default

    this.name is referring to the String name inside the method to replace the value of String name.

Similar Threads

  1. Replies: 3
    Last Post: 10-12-2010, 04:21 PM
  2. Replies: 1
    Last Post: 01-21-2010, 09:20 AM
  3. Replies: 2
    Last Post: 10-08-2009, 11:28 PM
  4. Replies: 2
    Last Post: 01-24-2009, 06:56 PM
  5. Replies: 1
    Last Post: 10-20-2008, 07:35 AM

Posting Permissions

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