Day07-2部分封装

    技术2025-04-27  23

    封装

    package com.oop.Demo04; //类 private 私有 public class Student { //名字 private String name; //学号 private int id; //性别 private char sex; //年龄 private int age; //学习() //睡觉() //提供一些可以操作这个属性的方法! //提供一些public 的 get ,set方法 //get 获得这个数据 public String getName(){ return this.name; } //set 给这个数据设置值 public void setName(){ this.name =name; } public void setName(String name) { this.name = name; } 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){ age =3; }else { this.age = age; } } } package com.oop; import com.oop.Demo03.Pet; import com.oop.Demo04.Student; //提高程序的安全性,保护数据 //隐藏代码的实现细节 //统一接口 //系统可维护增加了 public class Application { public static void main(String[] args) { Student student = new Student(); student.setName("阳光"); System.out.println(student.getName()); student.setAge(50); System.out.println(student.getAge()); } }
    Processed: 0.014, SQL: 9