Search code examples
javajavabeans

Can some one give me the Good Example of "Encapsulation" other than Java Bean?


For Encapsulation i see lot of examples which points Plain Java Bean (private members & public getters & setters) as example. But i think it's not a good example because having a private varibale with public getter & setter is as same as having public varibale it self. Can some one please help me in this regard ?


Solution

  • Encapsulation allows you to hide your programming behind a single class so that it is contained but also protected from outside interference.

    The example you state above is confusing to you because by creating getters and setters on the same private variable, you are in essence exposing your class (which is a no-no for good OO programming).

    Try this example instead:

    public class Door {
        private boolean locked;
        private boolean open;
    
        public boolean openDoor() {
            if (locked || open) {
                return false; //You can't open a locked or already open door
            }
            open = true;
            return true;
        }
    }
    

    Now in this (rather simple) example you are giving your end user a method called openDoor() that will allow them to interact with the door without giving them direct access to certain private variables that in reality control whether your door is open or even able to be opened.

    So you will still be interacting with those private variables but now your end user doesn't need to know anything about the mechanics of this door... only that they have an interface (through the openDoor() method) by which to manipulate the object.

    Incidentally, encapsulation adds a great benefit to your ability to maintain this Door class in the future. Say, for instance, you have another class (like a Person class) which depends on this openDoor() method. What if you need to add a new variable to the class to represent a second deadbolt variable?

    Without encapsulation you would need to edit both the Door class and the Person class that must interact with the new deadbolt variable in order to determine if the door could be opened. But with encapsulation, all maintenance can be kept internal to the Door class. The Person class never needs to know that openDoor() contains different logic than before.