DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 3 of 3
  1. #1
    Join Date
    Jun 2004

    Angry the "This" keyword

    Im new to java, this being my first semester, and i cant for the life of me figure out one of the applications of the "this" keyword. I understand its use in constructors as a way to overload them and pass parameters but when its used like:


    for instance, i have no idea what its supposed to be doing. Ive read my book but its little help on that one and my professor hasnt been returning my email so.....any help you could give would be greatly appreciated. Thanks!

  2. #2
    Join Date
    Jun 2004
    Ok my 2 cents, 'this' gives a java class the ability to refer to itself when performing an action ...

    Lets say you have the following class

    public class Test {
    //member field
    String copyright = null;

    Test(String copyright)//constructor

    Lets say that the chap who coded this class wanted the constructor to take the copyright parameter and assign it to a class field member of the same name.

    This wouldn't work. Why ? because of the scope of the parameter copyright variable, see java looks at that assignment and sees it as the local copyright (the copyright you passed as a parameter) assigning the same variable to itself. At then end of the constructor 'poof' the local copyright has gone out of scope and into limbo some place, and during this while the class member called copyright would not have been affected in any way.

    How would you tell java 'hey I need you to assign this to my class member' ? Enter the 'this' keyword.

    now if we changed the statement to

    this.copyright= copyright

    java now understands that you are trying to assign the parameter value to the member of the class rather than to the 'copyright' parameter itself.

    Hope that made sense....


  3. #3
    Join Date
    Jun 2004
    it did make sense, thank you very much

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center
Latest Articles
Questions? Contact us.
Web Development
Latest Tips
Open Source

   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center

We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.