Java 面向对象:封装详解 封装:属性私有,get/set 属性私有化提供get/set方法操作数据 优点:1.提高程序的安全性,保护数据2.隐藏代码的实现细节3.统一接口4.系统可维护性增加了 Student类 public class Student { //属性私有 private String name; private int age; private int sex; //设置set、get方法 public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getSex() { return sex; } public void setSex(int sex) { this.sex = sex; } } 运行类 public class Application { public static void main(String[] args) { Student student = new Student(); student.setName("张三"); student.setAge(20); student.setSex(2); System.out.println(student.getName()); System.out.println(student.getAge()); System.out.println(student.getSex()); } } 结果: