Search code examples
javaoopabstractioninformation-hidingdata-hiding

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?


Solution

  • Encapsulation = data hiding. Concealing information that doesn't need to be revealed to others in order to perform a 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.