Search code examples
javaencapsulation

I am confused about Encapsulation in Java


I looked into encapsulation many times, but still I'm not 100% clear about this topic.

My questions are:

What does getter really do? Say I only use getter but don't use setter, what will happen?

And same for setter. What does it really do, and how it manages to access private variable? If I only use setter but don't use getter, what will happen?

And also we have constructors in a class:

class Car {
     int x;
     Car(int x) {
        this.x = x;
     }
}

For me, it seems like constructor does the same thing as setter, although i "know" that it doesn't. Therefore, I wanted a clarification for this as well.


Solution

  • Encapsulation is controlling access to specific values using access modifiers. Consider the following:

    class Foo {
    public int v;
      public Foo(int v) {
         this.v = v;
      }
    }
    

    Now let an instance be created, Foo f = new Foo(20); One can access v simply by doing f.v. And it can be changed by doing f.v = 30;

    But what I for some reason v should be stored in a list or a string. You can't change it since it will break the class for existing users. So that is where getters come in.

    class Foo {
    private String v;
       public Foo(int v) {
         this.v = v+"";
       }
       public int getV() {
         return Integer.parseInt(v);
      }
    }
    

    The above is highly contrived but it illustrates that the internal handling of a value may be altered without affecting the user interface to access that value. So by using getters (and setters), one can do the following:

    • ensure that the user interface consistently returns the expected value without regard to its internal nature.
    • allows the user to set a value within specific limits. So a setter could enforce limitations on the value before accepting it.
    • making defensive copies to protect altering the internal values. E.g Don't return an array as one could make changes to the array as it is stored in the instance. Just return a copy of the array (or any other data structure for that matter).

    Imo, encapsulation is closely related to abstraction in that abstraction hides implementation details of how things are done. Encapsulation hides and/or protects methods and variables by imposing some form of access control.