Why are the get() and set() methods?

One of the three characteristics of object-oriented: encapsulation

Encapsulation: Encapsulate things into a class to reduce coupling and hide details. Keep a specific interface in contact with the outside world. When the internal interface changes, it will not affect the external caller.

Case:

package chapter02;

public class FengZhuang {
    public static void main(String[] args) {
        Student student = new Student();
        student.name = "小明";
        student.age = 120;
        student.printStudentAge();

        Student2 student2 = new Student2();
        student2.setName("小白");
        student2.setAge(120);
        student2.printStudentAge();
    }
}

class Student {
    String name;
    int age;

    public void printStudentAge() {
        System.out.println(name + "同学的年龄" + age);
    }
}

class Student2 {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if (age < 0 || age > 100) {
            throw new RuntimeException("年龄设置不合法");
        }
        this.age = age;
    }

    public void printStudentAge() {
        System.out.println(name + "同学的年龄" + age);
    }
}

Output result:
Insert picture description here

Conclusion: By privatizing the name and age attributes of the Student class, it can only be accessed through the public get/set method. In the get/set method, we can encapsulate the internal logic, and the external caller does not need to care about ours. Processing logic.

Guess you like

Origin blog.csdn.net/weixin_41699562/article/details/104029563