Encapsulation is one of the four fundamental Object-Oriented Programming (OOP) concepts. It refers to the bundling of data (variables) and methods that operate on that data into a single unit called a class. Additionally, encapsulation allows restricting access to certain details of an object's implementation while providing a controlled interface.
In Java, encapsulation is achieved by declaring the variables of a class as private
and providing public getter and setter methods to access and update the values of these variables. This helps in hiding the internal workings of an object and protecting the data from unauthorized access or modification.
Encapsulation is implemented by using the following steps:
private
.Letโs see an example of encapsulation in Java. We have a class Person with private fields for the name and age. We then provide public getter and setter methods to access and update these fields.
class Person { // Private fields private String name; private int age; // Getter method for name public String getName() { return name; } // Setter method for name public void setName(String name) { this.name = name; } // Getter method for age public int getAge() { return age; } // Setter method for age public void setAge(int age) { if(age > 0) { this.age = age; } else { System.out.println("Please enter a valid age."); } } }
In this example, we have private
fields name
and age
. The getter and setter methods allow controlled access to these fields. Notice the setAge
method validates the age before updating it.
Once encapsulation is applied, we can access the private fields of a class through getter and setter methods. Hereโs an example of how to create an object of the Person class and access the encapsulated data:
public class Main { public static void main(String[] args) { Person person = new Person(); // Setting values using setter methods person.setName("John"); person.setAge(25); // Getting values using getter methods System.out.println("Name: " + person.getName()); System.out.println("Age: " + person.getAge()); } }
In this example, we create a Person object and use the setter methods to assign values to name
and age
. We then use the getter methods to retrieve these values and print them.
While encapsulation focuses on hiding data and providing controlled access, inheritance allows one class to acquire the properties and methods of another class. Encapsulation deals with the internal workings of a class, whereas inheritance helps in building a relationship between classes.
Quick Tip:
Encapsulation helps in hiding the internal state of an object and provides a controlled interface through getter and setter methods. This ensures better data security, validation, and flexibility.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!