Benefits of Encapsulation
- Breaking functionality into small, maintainable units
- Grouping functions and data together
- Supporting testing of software at a granular【细粒度的】 level
Demo of Unencapsulated Code
public static void main(String[] args) {
Olive[] olives = {new Olive(), new Olive(), new Olive()};
OliveOil oil = new OliveOil();
OlivePress press = new OlivePress();
for (Olive olive: olives) {
olive.crush();
oil.add(olive);
}
}
Demo of Encapsulated Code
class OlivePress {
private Olive[] _olives;
public void OlivePress(Olive[] olives) {
this._olives = olives;
}
public OliveOil getOil() {
if (_olives == null) {
return null;
}
OliveOil oil = new OliveOil();
for (Olive olive:_olives) {
int yield = olive.crush();
oil.add(yield);
}
return oil;
}
}
public static void main(String[] args) {
OlivePress press = new OlivePress({new Olive(), new Olive(), new Olive()});
OliveOil oil = press.getOil();
}