You CAN do either one. However, your professor might appreciate using the methods instead of the direct access. Here's why.
Let's say you have a class like this:
class SomeClass {
private int someValue;
private String someString;
public SomeClass(int someValue, String someString) {
this.someValue = someValue;
this.someString = someString;
}
public int someValue() {
return this.someValue;
}
public String someString() {
return this.someString;
}
public String toString() {
return someValue + ": " + someString;
}
}
It's pretty straightforward, right? Well, what if all of a sudden we want to CHANGE the implementation of how we calculate someValue
, and base it off of someString
:
public int someValue() {
int value = 0;
for(int i = 0; i < someString.length; i++) {
if(someString.charAt(i) == ' ') value++;
}
return value;
}
Now you also have to change every place where variable someValue
was used.
So if you want to make the code easier to maintain in the long run, use the methods calls. This way when you code changes on you (and trust me, it changes all the time) you only have to change it in one spot instead of two.
And yes, you would want to use a method call in getting someString
instead of the direct access in the last method :-)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…