JavaFAQ Home » General Java
... When you return a Char, others can alter the Char
they received without modifying the Char, as stored in your application, because
Java uses pass by value to ...
Encapsulation is one of the tenets of object-oriented programming.
that objects should hide their inner workings from external view. Good
encapsulation increases code modularity by preventing objects from interacting
with each other in unexpected ways, which in turn makes future development
efforts and refactoring easier.
Getters and setters
The first step toward building objects with good encapsulation is to have the
getter/setter pair access private data fields. Requiring other objects that want
to read and write fields in your object to do so through a mechanism you control
allows you to enforce legal values and general internal data consistency.
have a field named duration that is expected to hold a positive integer,
you can throw an IllegalArgumentException when another object tries to
If you’ve left your duration member public, you can’t
prevent someone from calling yourObject.duration=-4 and messing up the internal
consistency of your data.
Immutability of return values
The data that your object makes available through method return values should
not be modifiable in a way that alters the internal state of your object.
Returning primitives provides no worry in this regard.
When you return a Char,
others can alter the Char they received without modifying the Char, as stored in
your application, because Java uses pass by value to return primitives.
However, when returning objects, you must be careful to monitor their
mutability. When an object’s value cannot be altered after instantiation, it
is said to be immutable.
Many of the objects in the java.lang package hierarchy
are immutable, including String, Char, and Short.
Making an object immutable requires three steps:
Read about it here at
Printer Friendly Page
Send to a Friend
Search here again if you need more info!