Case Study Encapsulation vs. Information Hiding vs. Abstraction vs. Hiding Data in Java

I know that there are many posts on this subject that have a theoretical explanation with real-time examples. These OOP terms are very simple, but more confusing for beginners like me. But I expect here not a definition and a real-time example, but a waiting piece of code in java .

Will someone please provide a very small piece of code for each of them in Java, which will help me understand a lot that Encapsulation vs Information Hiding vs Abstraction vs Data Hiding is practical?

+4
source share
2 answers

Encapsulation = information hiding = data hiding. Information that should not be known to others in order to perform a specific 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 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 associated with a type Car.

+15
source

To reduce confusion:

Encapsulation is used to hide information or hide data.

Encapsulation means on its own . All objects in Java have a set of data and methods for working with this data. Therefore, the user of any object does not need to worry about how the object works. Thus, you hide information and other difficulties.

: Java- , .

. , , specfic- , , .

: class Animal {} Lion Animal {}

, Lion , .. Animal.

givien KepaniHaole .

:

public interface Animal{
    public String getType();
}

class Lion implements Animal {
    private String animalType = "WILD";

    @Override
    public String getType() {
        return this.animalType;
    }
}
class Cow implements Animal {
    private String animalType = "Domestic";

    @Override
    public String getType() {
        return this.animalType;
    }
}

Lion Cow Animal. Lion Cow override getType Animal.

- , . , , , Animal, getType, , .. .

, , animalType Lion Cow, , , .

getType, . .

+5

All Articles