[上]JAVA学习系列模块八第一章158.封装_get&set方法的使用
视频
[vbilibili]【尚硅谷2024最新JAVA入门视频教程(上部)JAVA零基础入门教程】 https://www.bilibili.com/video/BV1YT4y1H7YM/?p=158&share_source=copy_web&vd_source=85f561e7442caa320f4a23b57edee129[/vbilibili]
笔记
2.问题:属性被私有化了,外界直接调用不了了,那么此时属性就不能直接赋值取值了,所以需要提供公共的接口
       get/set方法
      set方法:为属性赋值
      get方法:获取属性值
public class Person {
    private String name;
    private int age;
    //为name提供get/set方法
    public void setName(String xingMing) {
        name = xingMing;
    }
    public String getName() {
        return name;
    }
    //为age提供get/set方法
    public void setAge(int nianLing) {
        if (nianLing < 0 || nianLing > 150) {
            System.out.println("你脑子是不是秀逗啦!岁数不合理");
        } else {
            age = nianLing;
        }
    }
    public int getAge() {
        return age;
    }
}
public class Test01 {
    public static void main(String[] args) {
        Person person = new Person();
        //person.name = "涛哥";
        //person.age = -18;
        //System.out.println(person.name);
        //System.out.println(person.age);
        person.setName("涛哥");
        person.setAge(18);
        String name = person.getName();
        int age = person.getAge();
        System.out.println(name+"..."+age);
    }
}
小结:
用private将属性封装起来,外界不能直接调用,保护了属性
对外提供一套公共的接口(set/get方法),让外界通过公共的接口间接使用封装起来的属性

