My professor really emphasizes protecting against privacy leaks by always using accessors and mutators to access private instance variables; however, do I have to use the ge
If your class (or the accessor methods in question) is not final
, then you should definitely use the accessor methods.
If another class extends yours and overrides those accessors, your class should use the overridden accessors. If this would break your superclass, then your superclass is designed incorrectly; prevent those accessors from being overridden with final
, or change the design of your class.
No, you don't. You can access any variables, private, public or protected, from within the class.
Here are some tables to help you:
Source: Java Tutorials
It's normally not a good idea, for a number of reasons:
... but as always, there are exceptions. Some setters may have side-effects (for example setting a second value) that you WANT to execute, then it might be better to use the setter. Also, if you design your class for inheritance, it may be better to go via an accessor if you want the subclass to be able to alter the behavior.
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 :-)
I use a mix of both. Accessor methods add more clutter so I use them only when the variable is used many times. If the variable is used only once or twice I don't use them.
No you can use directly your instance variables inside the class, you're not violating any "rule". Getters and setters are mandatory for others classes to access instance variables of a class to not violate the encapsulation principle (which is quite important in OO programming).
In the end it's a matter of choice, but you're saving one method call using your first example.