java 封装

1,新建Application类,作为程序的入口

package oop.demo04;

public class Application {
    /*
    封装:
        1,提高程序安全性、保护数据
        2,隐藏代码的实现细节
        3,统一接口
        4,系统可维护性增加了;
     */
    public static void main(String[] args) {
        Student s1 = new Student();
        s1.setName("小向");
        System.out.println("name:"+s1.getName());

        s1.setAge(999);
        System.out.println("age:"+s1.getAge());
    }
}

2,新建Student类

package oop.demo04;

/*
学生类
 */
public class Student {
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public char getSex() {
        return sex;
    }

    public void setSex(char sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
       if (age>120 || age>0){
           System.out.println("你输入的年龄不合法");
       }else{
           this.age = age;
       }
    }

    /**
     * 属性
     * 名字
     * 学号
     * 性别
     * <p>
     * 方法
     * 学习()
     * 睡觉()
     */
//属性私有
    private String name;
    private int id;
    private char sex;
    private int age;

//    get/set
    public  String getName(){
        return  this.name;
    }

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

3,运行结果

原文地址:https://www.cnblogs.com/d534/p/15090101.html