Advertisement
//Java - Example of bad encapsulation
class Stats
{
public int weight; //weight with public access, can be accessed by anyone
public static void main(String... ar)
{
Stats ob = new Stats();
ob.weight = -100; //weight set to a negative value, legal but wrong.
}
}
Advertisement
//Java - Example of good encapsulation
class Stats
{
private int weight; //A private instance variable, weight
public getWeight() //A public getter method to get weight.
{
return weight;
}
public void setWeight(int wt) //A public setter method to set weight.
{
if(wt<0)
System.out.println("Please enter weight greater than zero");
else
weight=wt;
}
public static void main(String... ar)
{
Stats ob= new Stats();
ob.setWeight(-100);
}
}
Please enter weight greater than zero
interface food
{
public void cook();
}
class Soup implements Food
{
public void cook()
{
System.out.println("Cooking Soup");
}
}
class Pasta implements Food
{
public void cook()
{
System.out.println("Cooking Pasta");
}
}
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement