Java Encapsulation

Definition
Encapsulate the implementation details of the function to prevent the code and data from being randomly accessed by external classes.
To access the code and data of this class, you must pass strict interface control

Advantages
Reduced coupling,
easy to understand and maintain,
hide code details, control external access, and enhance security. The
internal structure can be freely modified.
Member variables are accurately controlled.

Steps to achieve Java encapsulation

  1. Modify the visibility of the attribute to restrict the access of the external class to the attribute (generally restricted to private)
  2. Create a pair of assignment methods for private attributes for external access

Instance

package TestEncapsulation;

public class EncapsulationPerson {
    
    
	// 设置为private,只有本类才能访问,外部无法直接访问
    private String name;
    private int age;

	// 外部类访问该类成员变量的入口,被称为getter和setter方法
    // 访问类中私有成员变量,都要通过这些getter和setter方法

    public void setAge(int age) {
    
    
        this.age = age;
        // this 解决实例变量(private String name)和局部变量(setName(String name)中的name变量)之间发生的同名的冲突
    }

    public int getAge() {
    
    
        return age;  // 不用加this
    }

    public void setName(String myName) {
    
    
        name = myName;  // 不同名,不需要加this
    }

    public String getName() {
    
    
        return name;
    }
}
package TestEncapsulation;

public class TestEncapsulation {
    
    
    public static void main(String[] args) {
    
    
        EncapsulationPerson person = new EncapsulationPerson();
        System.out.println("age: " + person.getAge());  // 实例变量,未赋值,会有默认值0
        person.setAge(23);
        System.out.println("age: " + person.getAge());

        System.out.println("name: " + person.getName());  // 实例变量,未赋值,会有默认值null
        person.setName("doudou");
        System.out.println("name: " + person.getName());

//        System.out.println(person.name);  // name 在 TestEncapsulation.EncapsulationPerson 中是 private 访问控制
    }
}

Guess you like

Origin blog.csdn.net/test121210/article/details/114160930