@anOOb wrote this in a comment ... and it deserves a thorough response.
I was pleasantly surprised when Java let me set a data member of one class from a difference class (in a separate file), since I didn't have to go through the hassle of creating an accessor. It's more convenient but isn't against one of the principles of OO?
It is actually deeper than OO. The principle is the principle of data encapsulation, and it applies to non-OO design as well.
The primary aim of accessors and mutators is to encapsulate the state; i.e. to prevent implementation details of a class from being visible outside of the class. There are two main reasons for doing this:
- It simplifies reasoning about the behavior of a class if you control or prevent access to its internal state.
It makes it easier to change the implementation type and invariants of a state variable. If the code that uses a class only uses accessors / mutators (i.e. getters / setters) to access the object state, then you can often make changes to the classes state representation and invariants while hiding the effects of the changes from the callers; e.g. here's a trivial example
private int counter;
public int getCounter() { return counter; }
becomes
private long counter;
public int getCounter() { return (int)counter; }
public long getLongCounter() { return counter; }
There are two more reasons we use accessors / mutators in Java:
An accessor or mutator method's behavior can typically be overridden in a subclass. By contrast, in Java you can't override or even change the visibility of an exposed attribute.
There are lots of frameworks / tools that depend on your classes having accessors and mutators with method names / signatures that follow the conventions of the JavaBeans spec.
It should also be noted that simple getter and setter methods are inlined by the JIT compiler, and therefore have minimal performance impact.
You should not think of creating accessors as a "hassle" that you should try to avoid. In fact, accessors (and mutators) are an important part of writing good quality Java code. This is considered to be "best practice", and typical style / bug checker programs will flag exposed state variables as problems.