1 封装
封装:将类的某些信息隐藏在类内部,不允许外部程序直接访问,而是通过该类提供的方法来实现对隐藏信息的操作和访问。
封装的步骤
[1]属性私有化
[2]提供公共的设置器和访问器
[3]在设置器和访问器中添加业务校验逻辑
public class Dog{ // 【1】private 私有的,对外不可见 private String name; private int health; private int love; private String strain; // 【2】提供公共的设置器(setter)和访问器(getter) public void setName(String name){ // 【3】逻辑校验 if(name.equals("")){ System.out.println("姓名不能为空."); }else{ this.name = name; } } public String getName(){ return this.name; } public void setHealth(int health){ if(health < 0){ System.out.println("健康值不合法."); this.health = 0; }else{ this.health = health; } } public int getHealth(){ return this.health; } public void setLove(int love){ if(love < 0){ System.out.println("亲密度不合法."); this.love = 0; }else{ this.love = love; } } public int getLove(){ return this.love; } public void setStrain(String strain){ if(strain.equals("")){ System.out.println("品种不能为空."); }else{ this.strain = strain; } } public String getStrain(){ return this.strain; } public Dog(){ } public Dog(String name,int health,int love,String strain){ this.setName(name); this.setHealth(health); this.setLove(love); this.setStrain(strain); } public void showInfo(){ System.out.print("我的名字叫"+this.name); System.out.print(",健康值"+this.health); System.out.print(",亲密度"+this.love); System.out.println(",我是一只"+this.strain); }}
2 静态常量
果一个量的值不会发生改变,可以把该量声明为静态常量,用static final修饰。
public class Penguin{ private String name; private int health; private int love; private String gender; static final String SEX_MALE = "雄"; static final String SEX_FEMALE = "雌"; public void setName(String name){ this.name = name; } public String getName(){ return this.name; } public void setHealth(int health){ if(health>100 && health<1){ this.health = 60; System.out.println("健康值必须在1-100之间,默认为60"); }else{ this.health = health; } } public int getHealth(){ return this.health; } public void setLove(String love){ this.love = love; } public int getLove(){ return this.love; } public void setGender(String gender){ this.gender = gender; } public String getGender(){ return this.gender; } public Penguin(){ } public Penguin(String name,String gender){ this.setName(name); this.setGender(gender); } public Penguin(String name,int health,int love,String gender){ this(name,gender); this.setHealth(health); this.setLove(love); } public void showInfo(){ System.out.print("我的名字叫"+name); System.out.print(",健康值"+health); System.out.print(",亲密度"+love); System.out.println(",性别"+gender); } }public class Test02{ public static void main(String[] args){ Penguin penguin = new Penguin("大脚",100,0,Penguin.SEX_MALE); }}