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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With