Encapsulation refers to a method of packaging and hiding the implementation details of an abstract functional interface.
(Recommended tutorial:java introductory tutorial)
The main function of encapsulation is that we can modify our own implementation code without modifying the program fragments that call our code .
Advantages:
Good encapsulation can reduce coupling.
The structure inside the class can be modified freely.
Can provide more precise control over member variables.
Hide information and implement details.
(Learning video recommendation:java course)
Encapsulation steps
1. Modify the visibility of attributes to limit Access to attributes (generally restricted to private), for example:
public class Person { private String name; private int age; }
In this code, the name and age attributes are set to private, which can only be accessed by this class, and no other class can access it. This way Information is hidden.
2. Provide external public method access to each value attribute, that is, create a pair of assignment methods for access to private attributes, for example:
public class Person{ private String name; private int age; public int getAge(){ return age; } public String getName(){ return name; } public void setAge(int age){ this.age = age; } public void setName(String name){ this.name = name; } }
Use this key The word is to resolve the conflict of the same name between the instance variable (private String name) and the local variable (name variable in setName(String name)).
The above is the detailed content of What does java encapsulation mean?. For more information, please follow other related articles on the PHP Chinese website!