Encapsulation is a way to protect data in a computer program. It means grouping data and code together in a special way so that the data is only accessible by the code inside that group, and not by code outside of it. Think of it like a shield that keeps the data safe.
To achieve encapsulation, programmers usually mark the data as "private," which means it can only be accessed by the code inside the group. Then they write "public" methods to allow other parts of the program to access the data indirectly, by calling these methods. This way, the data is kept safe from unauthorized access.
Here's an example of encapsulation in a Java program:
csharppublic class Encapsulate
{
private String geekName;
private int geekRoll;
private int geekAge;
public int getAge()
{
return geekAge;
}
public String getName()
{
return geekName;
}
public int getRoll()
{
return geekRoll;
}
public void setAge( int newAge)
{
geekAge = newAge;
}
public void setName(String newName)
{
geekName = newName;
}
public void setRoll( int newRoll)
{
geekRoll = newRoll;
}
}
In this program, the data is hidden from other parts of the program using the "private" keyword. The methods that allow access to the data are marked "public." This way, the data is kept safe and only accessible through these methods.
To use the program, you can create an object of the Encapsulate class and then call its methods to access the data:
csharppublic class TestEncapsulation
{
public static void main (String[] args)
{
Encapsulate obj = new Encapsulate();
obj.setName("Harsh");
obj.setAge(19);
obj.setRoll(51);
System.out.println("Geek's name: " + obj.getName());
System.out.println("Geek's age: " + obj.getAge());
System.out.println("Geek's roll: " + obj.getRoll());
}
}
In this program, we create an object called "obj" of the Encapsulate class. We then call its methods to set the values of the data (geekName, geekAge, and geekRoll) and then print them out.
Encapsulation has several advantages. Firstly, it hides the inner workings of a class from the rest of the program, which makes the program more secure. Secondly, it allows for more flexibility, because you can make certain data read-only or write-only. Thirdly, it makes the code more reusable and easier to change. Finally, it makes testing easier because encapsulated code is easier to test.