Practical example Encapsulation vs Information Hiding vs Abstraction vs Data Hiding in Java

Prashant Shilimkar picture Prashant Shilimkar · Nov 13, 2013 · Viewed 22.8k times · Source

I know there are lots of post regarding this question which has theoretical explanation with real time examples.These OOPs terms are very simple but more confusing for beginners like me. But I am expecting here not a definition and real time example BUT expecting code snippet in java.

Will anyone please give very small code snippet for each one in Java that will help me a lot to understand Encapsulation vs Information Hiding vs Abstraction vs Data Hiding practically?

Answer

yamafontes picture yamafontes · Nov 13, 2013

Encapsulation = information hiding = data hiding. Information that doesn't need to be known to others in order to perform some task.

class Girl {
  private int age;
  Girl(int age) {
    this.age = age;
  }
  public boolean willGoOutWithGuy(boolean isGuyUgly) {
    return (age >= 22) && (!isGuyUgly);
  }
}

class Guy {
  private Girl girl = new Girl();
  private boolean isUgly = true;
  public boolean willGirlGoOutWithMe() {
    return girl.willGoOutWithGuy(isUgly);
  }
  // Guy doesn't have access to Girl's age. but he can ask her out. 
}

Abstraction = different implementations of the same interface.

public interface Car {
  public void start();
  public void stop();
}

class HotRod implements Car {
  // implement methods
}

class BattleTank implements Car {
  // implement methods
}

class GoCart implements Car {
  // implement methods
}

The implementations are all unique, but can be bound under the Car type.