Java Encapsulation
In object-oriented programming methods, encapsulation (English: Encapsulation) refers to a method of wrapping and hiding the implementation details of an abstract function interface.
Encapsulation can be regarded as a protective barrier that prevents the code and data of the class from being randomly accessed by code defined by external classes.
To access the code and data of the class, you must go through strict interface control.
The main function of encapsulation is that we can modify our own implementation code without having to modify the program segments that call our code.
Proper encapsulation can make code easier to understand and maintain, and also enhances code security.
Advantages of Encapsulation
1. Good encapsulation can reduce coupling.
2. The internal structure of the class can be freely modified.
3. Member variables can be controlled more precisely.
4. Hide information and implementation details.
Steps to Achieve Encapsulation in Java
1. Modify the visibility of attributes to restrict access to attributes (generally restricted to private), for example:
In this code, thenameandageattribute is set to private; only this class can access it, while other classes cannot, thus hiding the information.
2. For each value attribute, provide public methods for external access, that is, create a pair of getter and setter methods for accessing private attributes, for example:
Usingthisthe keyword is used to resolve the same-name conflict between the instance variable (private String name) and the local variable (the name variable in setName(String name)).
Example
Let's look at an example of a Java encapsulation class:
EncapTest.java file code:
In the above example, public methods are the entry point for external classes to access the member variables of the class.
Usually, these methods are called getter and setter methods.
Therefore, any class that wants to access the private member variables of the class must go through these getter and setter methods.
The following example illustrates how the variables of the EncapTest class are accessed:
RunEncap.java file code:
The result of compiling and running the above code is as follows:
Name : James Age : 20Other Extensions