1.属性私有,get/set
2.封装:数据的隐藏
3.该漏漏,该藏藏:程序要求高内聚、低耦合,高内聚指类的内部数据操作细节自己完成,低耦合是提供少量方法供外部使用
package com.wuming.oop.demo04; //类 private:私有 public class Student { //属性私有 private String name;//名字 private int id;//学号 private char sex;//性别 private int age; public int getAge() { return age; } public void setAge(int age) { if (age>120 || age<0){//不合法 this.age=3; }else{ this.age = age; } } //alt+insert public int getId() { return id; } public void setId(int id) { this.id = id; } //提供一些可以操作这个属性的方法 //提供一些public的get、set方法 //get获取这个数据 public String getName(){ return this.name; } //set给这个数据设置值 public void setName(String name){ this.name=name; } }
同一个包下再创一个类
package com.wuming.oop.demo04; public class Application { public static void main(String[] args) { Student s1 = new Student(); s1.setName("秦僵"); System.out.println(s1.getName()); s1.setAge(-1);//不合法的 System.out.println(s1.getAge()); } }
秦僵
3