Encapsulation
Encapsulation in Java
Encapsulation is a fundamental concept in object-oriented programming (OOP) that helps make your code more modular, secure, and manageable.
What is Encapsulation?
Encapsulation is the process of wrapping data (variables) and code (methods) that manipulates the data into a single unit, typically a class. It also means restricting direct access to some of the object's components and only allowing them to be modified through specific methods.
Key Features of Encapsulation
Data Hiding:
- Encapsulation hides the internal state of the object from the outside world. This means that the internal data of an object is protected from unintended or harmful modifications.
Controlled Access:
- Access to the data is controlled through public methods. This ensures that the data can only be accessed or modified in a controlled manner.
Modularity:
- Encapsulation helps in breaking down the program into smaller, manageable pieces or modules.
How to Implement Encapsulation in Java
To implement encapsulation in Java, follow these steps:
- Declare the variables of a class as private: This hides the data from other classes.
- Provide public getter and setter methods: These methods allow controlled access to the private variables.
Example of Encapsulation
Here’s a simple example to illustrate encapsulation in Java:
Step-by-Step Example
Define a Class with Private Variablespublic class Person {
private String name; // Private variable
private int age; // Private variable
// 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) { // Simple validation
this.age = age;
}
}
}
public class Main {
public static void main(String[] args) {
// Create an object of the Person class
Person person = new Person();
// Set values using setter methods
person.setName("Alice");
person.setAge(30);
// Get values using getter methods
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
// Trying to set an invalid age
person.setAge(-5);
System.out.println("Updated Age: " + person.getAge()); // Age will not change due to validation
}
}
Comments
Post a Comment