Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between information hiding and encapsulation? [duplicate]

I know there is a difference due to research but I can only find similarities between them... I was hoping if someone would clarify the difference and if you can an example for each would really help. Java program please also would this program count as encapsulation or information hiding or even both

 class DogsinHouse {
   private int dogs;
   public int getdog() {
     return dogs;
   }

   public void setdog(int amountOfDogsNow) {
     dogs = amountOfDogsNow;
   }
 }
like image 872
Zero Avatar asked Oct 30 '22 14:10

Zero


1 Answers

The code portion you post is an example of both. Encapsulation is the technique for which a Java class has a state (informations stored in the object) and a behaviour (the operations that the object can perform, or rather the methods). When you call a method, defined in a class A, in a class B, you are using that method without knowing its implementation, just using a public interface.

Information Hiding it's the principle for which the istance variables are declared as private (or protected): it provides a stable interface and protects the program from errors (as a variable modification from a code portion that shouldn't have access to the above-mentioned variable).

Basically:

Encapsulation using information hiding:

public class Person {
    private String name;
    private int age;

    public Person() {
    // ...
    }

    //getters and setters
 }

Encapsulation without information hiding:

public class Person {
    public String name;
    public int age;

    public Person() {
    // ...
    }

    //getters and setters
 }

In the OOP it's a good practice to use both encapsulation and information hiding.

like image 168
andy Avatar answered Nov 15 '22 04:11

andy