Encapsulation is a process of wrapping code and data together into a single unit. Encapsulationis used to bind method and variables(data). Below is my sample code to demonstrate Encapsulation in java, in this first I have created food class and food related data - name taste, price and taste defined in String and then in next step I have created calculateCost() method , all behaviour of food bind in single unit or say calculateCost() method. In the below example I have fully described "how can use Enapsulation in java".
public class Food {
private String name;
private String price;
private String taste;
private Food(String name, String price, String taste) {
this.name = name;
this.price = price;
this.taste = taste;
}
public void calculateCost() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getTaste() {
return taste;
}
public void setTaste(String taste) {
this.taste = taste;
}
}
0 Comment(s)