面向对象(封装) 该露的露,该藏得藏 我们程序设计要求"高内聚,低耦合"。高内聚就是类的内部数据操作细节自己完成,不允许外部干涉;低耦合:仅暴露少量的方法给外部使用。 封装(数据的隐藏) 通常,应禁止直接访问一个对象中数据的实际显示,而应通过操作接口来访问,这称为信息隐藏。 记住这句话:属性私有,get/set package com.baidu.www.oop03; public class Application { public static void main(String[] args) { Student s1 = new Student(); s1.setName("刘"); System.out.println(s1.getName()); s1.setAge(999); //输出3 System.out.println(s1.getAge()); } } package com.baidu.www.oop03; //类: private:私有 public class Student { //属性私有 private String name; private int id; private char sex; private int age; //提供一些可以操作这个的方法 //提供一些public的get、set方法 //get获得这个数据 //set给这个数据 public String getName() { return 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){ this.age = age; }else { this.age=3; } } }