java:access_specifiers_accessors_and_mutators
Differences
This shows you the differences between two versions of the page.
Next revision | Previous revisionNext revisionBoth sides next revision | ||
java:access_specifiers_accessors_and_mutators [2020/09/12 01:27] – created mithat | java:access_specifiers_accessors_and_mutators [2020/09/12 01:32] – old revision restored (2020/09/12 01:30) mithat | ||
---|---|---|---|
Line 1: | Line 1: | ||
- | ====== | + | ====== |
- | ===== Access | + | ===== Access |
- | The '' | + | The '' |
+ | |||
+ | <file java ClickerCounter.java> | ||
+ | public class ClickerCounter { | ||
+ | |||
+ | int count; | ||
+ | |||
+ | void click(){ | ||
+ | count++; | ||
+ | } | ||
+ | |||
+ | void reset(){ | ||
+ | count = 0; | ||
+ | } | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | But the definition has issues. For example, if we change our example as follows: | ||
<file java ClickerExample.java> | <file java ClickerExample.java> | ||
Line 20: | Line 37: | ||
</ | </ | ||
- | 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 | + | 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 |
+ | |||
+ | 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