Home >Java >javaTutorial >Understanding Encapsulation in Object-Oriented Programming
Encapsulation is a fundamental object-oriented programming concept that involves bundling data (fields) and methods (functions) that operate on the data within a single unit, typically a class. It restricts direct access to some of the object's components, making it easier to maintain and secure the code.
// Encapsulation refers to restricting access of a class from the outside world public class Person { private String name; private String profession; private double height; private int ID; private int age; // Constructor public Person(String name, String profession, double height, int iD, int age) { this.name = name; this.profession = profession; this.height = height; ID = iD; this.age = age; } // Getters and setters for accessing private fields public String getName() { return name; } public void setName(String name) { this.name = name; } public String getProfession() { return profession; } public void setProfession(String profession) { this.profession = profession; } public double getHeight() { return height; } public void setHeight(double height) { this.height = height; } public int getID() { return ID; } public void setID(int iD) { ID = iD; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } // Main method to demonstrate encapsulation public static void main(String[] args) { Person myPerson = new Person("Robert", "doctor", 130.4, 39, 23); // Accessing private fields through getter methods System.out.println(myPerson.getName()); System.out.println(myPerson.getProfession()); System.out.println(myPerson.getID()); System.out.println(myPerson.getAge()); } }
The fields name, profession, height, ID, and age are declared as private. This makes them inaccessible directly from outside the class.
Public methods like getName(), setName(), getProfession(), and others act as controlled access points for the private fields. These methods allow external code to retrieve and modify the private data securely.
The constructor initializes the fields when an object of the class Person is created. This ensures that the object starts in a valid state.
The main method demonstrates how encapsulation is used. The private fields are accessed indirectly through the getter methods.
Data Protection:
Controlled Access:
public void setAge(int age) { if (age > 0) { this.age = age; } else { System.out.println("Age must be positive."); } }
Code Flexibility:
This example illustrates how encapsulation ensures that the Person class maintains integrity and hides its implementation details while providing a controlled interface for interaction.
The above is the detailed content of Understanding Encapsulation in Object-Oriented Programming. For more information, please follow other related articles on the PHP Chinese website!