One, what is encapsulation?
Encapsulation is the privatization of attributes, which provides a public way to access private properties.
The approach is to modify the visibility of the property to restrict access to the property and create a pair of value (getter) and assignment (setter) methods for each property for access to those properties.
such as: private String name;
Copy Code code as follows:
Public String GetName () {
Return
}
public void SetName (String name) {
This.name=name;
}
Second, why the need for encapsulation
By encapsulation, the data access restrictions on attributes can be achieved, while the maintainability of the program is increased.
Because the value method and the assignment method hide the implementation changes, it does not affect the class that reads or modifies the property, avoids large-scale modifications, and increases the maintainability of the program.
What does this keyword mean?
Sometimes a method needs to refer to the object that calls it. To do this, Java defines this keyword. To put it simply,
This is a reference that refers to itself within an object. You can directly reference an object to resolve any conflict with the same name that occurs between an instance variable and a local variable.
Iv. How to implement encapsulation and implement the specific methods of encapsulation
(1), modify the visibility of the property to restrict access to the property.
(2) Create a pair of assignment and value methods for each property for access to these properties.
(3), in the assignment and the value method, adds the restriction which the attribute accesses.
The above mentioned is the entire content of this article, I hope you can enjoy.
Please take a moment to share the article with your friends or leave a comment. We will sincerely thank you for your support!