So if your class has an instance variable you would create an appropriate getter and setter method - its that whole encapsulation madness at play here. Convention is a mixed case method name with get and set used as the prefix on the method name.
Code:
public class MutatorExample {
private String myField;
/**
* Accessor/Getter
*/
public String getMyField() {
return myField;
}
/**
* Mutator/Setter
*/
public void setMyField(String myField) {
this.myField = myField;
}
}
Exactly why is this better ? So you can reference member fields by a pseudonym rather than method calls, so what. Heck might as well just make your member public and access it directly. I fail to see your beef.
Exactly why is this better ? So you can reference member fields by a pseudonym rather than method calls, so what. Heck might as well just make your member public and access it directly. I fail to see your beef.
Well that was just a simple example. The point is that I can still protect the internals of my class yet have the simplicity of p.Name rather than p.getName. If the field at hand can be mutated, maybe you want to send a clone of it rather than the field itself, etc. You can put any code you want in the get/set blocks, just as in getName and setName, but still access the field in a clean way that looks like you just made the field public.
Another example: suppose a class had counter variable count that needed to be incremented. I could define a method called incrementCount, or I could do this:
Code:
p.Count++;
In Java the equivalent would be
Code:
p.setCount(p.getCount()+1);
Also note that I don't have to use BOTH get and set. Maybe I wanted read only access to the name. So I could still be able to read p.Name, just not set to it, which you couldn't do by just making the field public to get this simplicity.
A minor point, I agree, but any efforts to keep code neat and simple is worthwhile.
Just wanted to throw out my 2 cents here. It is better to return a copy of your variable instead of the actual variable. If you return your private variable the caller method can now modify the classes private variable.