User Tools

Site Tools


java:access_specifiers_accessors_and_mutators

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
java:access_specifiers_accessors_and_mutators [2020/09/12 01:41] – [Access modifiers] mithatjava:access_specifiers_accessors_and_mutators [2020/09/12 02:01] (current) – [this] mithat
Line 235: Line 235:
 ===== this ===== ===== this =====
  
-FIXME+Every class has an automatically generated ''this'' member variable that points to the object it's associated with. In other words, it's a reference back to the object itself.
  
 +''this'' can be used to simplify writing mutators and other methods that have parameters because it eliminates the need to come up with new names for parameters. Let's see how this works by modifying the ''setMaxCount()'' method.
  
-Copyright © 2011-2018 Mithat Konar. All rights reserved.+ 
 +<code java> 
 +public void setMaxCount(int maxCount) { 
 +    if (maxCount > 0) { 
 +        this.maxCount = maxCount; 
 +    } else { 
 +        System.out.println("Invalid maximum count: " + maxCount); 
 +    } 
 +
 +</code> 
 + 
 +We have changed the name of the parameter to ''maxCount''. Inside the method it shadows the member variable ''maxCount'', but we can still access the member variable through the ''this'' reference. In essence, what we are saying in the above is, "Set this object's maxCount to the maxCount we passed in." 
 + 
 +''this'' will be used in other ways as well, so get comfortable with it. Think of it as meaning, "this object"
 + 
 +Copyright © 2020 Mithat Konar. All rights reserved.
java/access_specifiers_accessors_and_mutators.1599874863.txt.gz · Last modified: 2020/09/12 01:41 by mithat

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki