封装
该露的露,该藏的藏
“高内聚,低耦合”:高内聚:类的内部数据操作细节自己完成,不允许外部干涉;低耦合:仅暴露少量的方法给外部使用。
属性私有,get/set
Student方法里面:
不私有的话,可以直接在main方法里面s1.name;私有之后就必须在方法里面使用get/set,然后在main方法里面使用s1.getname
package demo03; public class Student { //private:属性私有 private String name; private int id; //get获得这个数据 public String getName(){ return this.name; } //set给这个数据设置值 public void setName(String name){ this.name=name; } }
main方法里面
import demo03.Student; public class Application { public static void main(String[] args) { Student s1=new Student(); String name=s1.getName(); s1.setName("lh");//在这里设置,传入名字; System.out.println(s1.getName()); } }