Reputation: 13
I'm just wondering, what is the difference between using a setter method, setLocationCells
, and simply declaring an int array called locationCells
with the values {2,3,4}?
Here is the code using setter method (The first class is the main class):
public static void main(String[] args) {
SimpleDotCom dot = new SimpleDotCom();
int[] locations = {2,3,4}; // these are the location cells we will pass in
dot.setLocationCells(locations); // locationCells now 2,3,4
String userGuess = "2";
String result = dot.checkYourself(userGuess);
}
Second class:
int[] locationCells;
int numOfHits = 0;
public void setLocationCells(int[] locs) {
locationCells = locs;
}
public String checkYourself(String stringGuess) {
int guess = Integer.parseInt(stringGuess);
String result = "miss";
for (int cell : locationCells) {
if (guess == cell) {
result = "hit";
numOfHits++;
break;
}
}
if(numOfHits == locationCells.length) {
result = "kill";
}
System.out.println(result);
return result;
}
Now, without setter method:
public static void main(String[] args) {
SimpleDotCom dot = new SimpleDotCom();
String userGuess = "2";
String result = dot.checkYourself(userGuess);
}
Second class:
int[] locationCells = {2,3,4};
int numOfHits;
public String checkYourself(String stringGuess) {
int guess = Integer.parseInt(stringGuess);
String result = "miss";
for (int cell : locationCells) {
if (guess == cell) {
result = "hit";
numOfHits++;
break;
}
}
if(numOfHits == locationCells.length) {
result = "kill";
}
System.out.println(result);
return result;
}
Any help is appreciated, thank you so much!
Upvotes: 1
Views: 339
Reputation: 830
Since there are many ways you can assign Object members, using getters and setters just helps simplify the contract between the internals of the Class and those that work with it. This is done by just exposing an interface and usually declaring the Class members as private.
If you change the way these members are assigned later on, provide data validations, conversions, you do not have to worry about changing every other place that assigns them, you just update the internal implementation of the setter or getter. Your example seems trivial, correct, but setters and getters help reduce complexity as projects grow. It provides a safer contract when you use an interface since you can handle all sorts of subtle conditions aside from just data types, such as what the state should be when the value is 0, or the member reference is null.
The design principle here is called encapsulation.
Upvotes: 1