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

Next revision
Previous revision
Next revisionBoth sides next revision
java:access_specifiers_accessors_and_mutators [2020/09/12 01:27] – created mithatjava:access_specifiers_accessors_and_mutators [2020/09/12 01:33] – [Access modifiers] mithat
Line 1: Line 1:
-======  Access Specifiers, Accessors, and Mutators ====== +======  Access Modifiers, Accessors, and Mutators ====== 
  
-===== Access specifiers ===== +===== Access modifiers ===== 
-The ''ClickerCounter'' class definition we used previously encapsulates the state and behavior of a clicker counter as an object should. But the definition has issues. For example, if we change our example as follows:+The ''ClickerCounter'' class definition we used previously encapsulates the state and behavior of a clicker counter as an object should. 
 + 
 +<file java ClickerCounter.java> 
 +public class ClickerCounter { 
 +     
 +    int count; 
 +     
 +    void click(){ 
 +        count++; 
 +    } 
 +     
 +    void reset(){ 
 +        count = 0; 
 +    }     
 +
 +</file> 
 + 
 +But the definition has issues. For example, if we change our ''main'' code as follows:
  
 <file java ClickerExample.java> <file java ClickerExample.java>
Line 20: Line 37:
 </file> </file>
  
-the object will happily oblige the user's wish to set the count to some arbitrary value. That's not something you can typically do with a clicker counter. In other words, the object offers no **protection** of its state. This is easy enough to solve with Java's access modifiers. Let's look at a modified version of our class definition that gives us some protection using access modifiers:+the object will happily oblige the user's wish to set the count to some arbitrary value. That's not something you can typically do with a clicker counter and probably not what you want out from your ''ClickerCounter'' object. In other words, the object offers no **protection** of its state. 
 + 
 +This is easy to solve with Java's access modifiers. Let's look at a modified version of our class definition that gives us some protection using access modifiers:
  
 <file java ClickerCounter.java> <file java ClickerCounter.java>
java/access_specifiers_accessors_and_mutators.txt · Last modified: 2020/09/12 02:01 by mithat

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki