encapsulation and abstraction OOPs concept

Mishthi picture Mishthi · Oct 11, 2010 · Viewed 12.2k times · Source

Does Encapsulation is information Hiding or it leads to information hiding??

As we say that Encapsulation binds data and functions in a single entity thus it provides us control over data flow and we can access the data of an entity only through some well defined functions. So when we say that Encapsulation leads to abstraction or information hiding then it means that it gives us an idea which data to hide and which data to show to users... coz the data that users cant access can be hidden from them thus encapsulation gives us a technique to find out what data to be hidden and what should be visible... Is this concept correct??

And what is the difference between information hiding and abstraction??

Answer

ivorykoder picture ivorykoder · Oct 11, 2010

Possible duplicate of the this

public class Guest {
  private String name;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }
}

See the above code, we have encapsulated the String name, we provide the access to it through public methods.

Say we have created object of Guest called guest. Then the following will be illegal.

System.out.println("Guests name  : "guest.name);

Access through public methods is what can only be done.

guest.getName();

Benefits of Encapsulation:

  1. The fields of a class can be made read-only or write-only.

  2. A class can have total control over what is stored in its fields.

  3. The users of a class do not know how the class stores its data. A class can change the data type of a field, and users of the class do not need to change any of their code.