Encapsulation is one of the fundamental principles of object-oriented programming (OOP) and refers to the practice of hiding the internal implementation details of a class and providing a well-defined interface for interacting with that class. In other words, encapsulation protects the internal state of an object and restricts direct access to its members (attributes and methods).
Main concepts associated with encapsulation:
Private Attributes
Attributes of a class are often declared "private". This means they can only be accessed directly within the class itself.
public class Person {
private String name;
private int age;
// methods getter and setter to access and modify the attributes
public String getName() {
return name;
}
public void setName(String newName) {
this.name = newName;
}
public int getAge() {
return age;
}
public void setAge(int newAge) {
this.age = newAge;
}
}
Getter e Setter
"Getter" methods are used to obtain the value of a private attribute, while "setter" methods are used to modify that value. This allows control of access and modification of attributes.
Access control
Encapsulation helps control access to a class's internal members by ensuring that only specific methods (such as getters and setters) or related classes can directly interact with attributes.
Protection against Unwanted Modifications
By encapsulating implementation details, a class can protect its attributes from unwanted modifications or direct manipulation errors.
Encouraging the Use of Methods
Encapsulation encourages interaction with objects through methods, promoting a more modular design and facilitating future updates or internal changes without affecting external code.
Encapsulation example:
public class EncapsulationExample {
public static void main(String[] args) {
Person person = new Person();
person.setName("John");
person.setAge(25);
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
}
}
In this example, encapsulation is applied to the "Person" class, where the internal details (name and age) are encapsulated, and access and modification of these details are controlled by the "getName()", "setName()", "getAge()", and "setAge()" methods. This provides a high level of control over how attributes are accessed and modified, while maintaining a clear interface for external interaction.
Nenhum comentário:
Postar um comentário