DEV Community

Discussion on: Explain Encapsulation and Polymorphism Like I'm Five

Collapse
 
carlosmgspires profile image
Carlos Pires

Encapsulation:

Joey's Mom is making lunch: a bit of meatloaf, with mashed potatoes, peas and a couple of carrot slices.

/* @author Mom */
public class Lunch {
    public var pieces = Array;
    private var nutrients = 0;

    public function __construct(todaysLunchPieces) {
        this.pieces = ArrayCopy(todaysLunchPieces);
        this.nutrients = CalculateNutrients(todaysLunchPieces);
    }

    public function eat() {
        return nutrients;
    }

    public function toString() {
        return this.pieces;
    }
...

}

JoeysLunch = new Lunch(['meatloaf', 'mashed potatoes', 'carrots', 'peas']);

Joey asks what's for lunch. Mom answers "Meatloaf, mashed potatoes, carrots, peas". Joey doesn't like peas. He starts picking them and surreptitiously giving them to the dog under the table.

/* @author Joey */
print(JoeysLunch);
JoeysLunch.pieces = ['meatloaf', 'mashed potatoes', 'carrots'];
myNutrients += JoeysLunch.eat();
...

Joey's Mom sees Joey's lunch hack, and says:
"OK, Joey... you don't have to eat the peas, if you don't want to. Gimme your plate."

Next day... Joey's Mom takes all the peas, carrots and leftover mashed potatoes, and grinds them into a nutritious and healthy soup...
Joey's Mom as refactored Lunch:

/* @author Mom */
public class Lunch {
    private var pieces = Array;
    private var nutrients = 0;
    private var description = '';

    public function __construct(todaysLunchPieces, description) {
        this.pieces = ArrayCopy(todaysLunchPieces);
        this.nutrients = CalculateNutrients(todaysLunchPieces);
        this.description = description;
    }

    public function eat() {
        return nutrients;
    }

    public function toString() {
        return this.description;
    }
...

}

JoeysLunch = new Lunch(['meatloaf', 'mashed potatoes', 'carrots', 'peas'], 'Soup');

Now Joey can't change the internal state of his Lunch.
He is only allowed to eat() and only has access to the output of eat() and to a general description of what Lunch is. He can't remove the peas from the soup because the peas are now encapsulated.