5

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;
   }
 }
charliebrownie
  • 5,777
  • 10
  • 35
  • 55
Zero
  • 53
  • 4
  • 7
    You may want to read [Abstraction, Encapsulation, and Information Hiding](http://www.tonymarston.co.uk/php-mysql/abstraction.txt) – Edwin Dalorzo Nov 30 '15 at 02:20
  • 1
    Short answer: information hiding (also called data privacy) refers to using access modifiers like public, protected, and private to restrict access to members (method and fields). Encapsulation refers to collecting related state and behavior together into a single "capsule" which, in OOP, refers to an class which encapsulates the state and behavior that it needs to do its job. Related concepts are coupling and cohesion. – Bobby StJacques Nov 30 '15 at 04:02

1 Answers1

2

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.

andy
  • 269
  • 1
  • 12
  • 22