Encapsulation Example. Giovanni Doria - acorrell5106/preAPCS-1516 GitHub Wiki

Encapsulation can be used to set fields in a class private, and using these fields with public methods. These fields cannot be used outside the class and are "hidden" from the class. Encapsulation also acts like a protective barrier that keeps the code from being accessed by "outside code", that is not declared in its own class. With this, Encapsulation can have the benefit of being able to modify your code without breaking it when others use your code.

Example:

public class Encapsulation {

private String food;

private String drink;

private double cost;

public String getfood() {

return food;

}

public String getdrink() {

return drink;

}

public double getcost() {

return cost;

}

public void setfood(String namefood){

food = namefood;

}

public void setdrink(String namedrink){

drink = namedrink;

}

public void showcost(double showcost){

cost = showcost;

}

}

Calling:

public class callEncapsulation {

  public static void main(String [] args) {

      Encapsulation en = new Encapsulation();

      en.showfood(" Pizza ");

      en.showdrink(" Water ");

      en.showcost(" 5 ");

      System.out.println(" Your food is " + en.getfood() + " with a " + en.getdrink() + " that cost $ " + en.getcost());

}

}