Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 807
Prashant Shilimkar Avatar asked Nov 29 '22 00:11

Prashant Shilimkar


1 Answers

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

class Bartender {
  private boolean hasBeer = false;
  public boolean willGiveBeerToDrinker(int drinkerAge) {
    return (hasBeer && (drinkerAge >= 21));
  }
}

class Drinker {
  private Bartender bartender = new Bartender();
  private int age = 18;
  public boolean willBartenderGiveMeBeer() {
    return bartender.willGiveBeerToDrinker(age);
  }
  // Drinker doesn't know how much beer Bartender has
}

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.

like image 196
yamafontes Avatar answered Dec 09 '22 13:12

yamafontes