5.7 成员属性封装

发布时间 2023-06-02 09:23:24作者: 盘思动
  • 类中成员属性,98%都会用private来封装,不让直接修改,只可以通过setter方法来修改成员属性的值。
class Person {
    private String name;// private 对外不可修改,对类内部是可见的;setter getter 设置或获得属性;
    private int age;// 98% 都需要封装的;
    public void tell(){
        System.out.println("姓名:" + name + ",年龄:" + age);
    }

    public void setName(String n ){
        name = n;
    }
    public void setAge(int a){
        if(a > 0)
            age = a;
    }
    public String getName(){
        return name;
    }
    public int getAge(){
        return age;
    }

}

public class ImoocStudent {

    public static void main(String[] args) throws Exception{
        Person per = new Person();// 实例化方法一
        per.setName("张三");// 这里用".",而不是“->”
        per.setAge(-33);
        per.tell();
    }

}