kingjr3 said:
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:
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.