In object-oriented programming methods, Encapsulation refers to a method that hides the implementation details of an abstract functional interface. Data is protected internally, hiding internal implementation details, and providing interfaces and external interactions to the outside.
Steps to use encapsulation
All attributes of the class are modified using the keyword private, turning them into private, and not allowing external classes to directly access the generated or provide public setter/getter methods to operate these hidden attributes. Add logical control to the class's own setter/getter method to ensure the validity and security of data access.
Let's look at an example of a Java encapsulation class:
/* File name: EncapTest.java */public class EncapTest{private String name;private String idNum;private int age;public int getAge(){return age;}public String getName(){return name;}public String getIdNum(){return idNum;}public void setAge( int newAge){age = newAge;}public void setName(String newName){name = newName;}public void setIdNum( String newId){idNum = newId;}}In the above example, the public method is the entrance to the external class to access the member variables of the class.
Typically, these methods are called getter and setter methods.
Therefore, any class that wants to access private member variables in a class must pass these getter and setter methods.
Use the following example to illustrate how the variables of the EncapTest class are accessed:
/* F file name: RunEncap.java */public class RunEncap{ public static void main(String args[]){ EncapTest encap = new EncapTest(); encap.setName("James"); encap.setAge(20); encap.setIdNum("12343ms"); System.out.print("Name : " + encap.getName()+ " Age : "+ encap.getAge()); }}The above code compilation and operation results are as follows:
Name : James Age : 20
Benefits of using package
1. Good packaging can reduce coupling
2. The structure inside the class can be freely modified.
3. More precise control of members can be given.
4. Hide information and implement details
Summarize
The above is all about the encapsulated code examples in the Java language. I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!