第一步:
添加private:私有的修改属性的可见性来限制对属性的访问
第二步:为每个属性创建一对复制方法和取值方法,用于对这些属性的访问(setter和get)
第三步:在赋值和取值方法中,加入对属性的存取限制
例如:public class Dog { private boolean mammal ; //哺乳动物 private boolean carnivorous;//食肉动物 private int numOfLegs ;//有几条腿 private int mood;//情绪属性 1:情绪不好,烦躁 2:情绪好 //参加私有属性的getter,setter方法 //判断是否哺乳动物 public boolean isMammal(){ return (mammal); } public void setMammal(boolean mammal) { } //判断是否食肉动物 public boolean isCarnivorous(){ return (carnivorous); } public void setCarnivorous(boolean carnivorous) { this.carnivorous = carnivorous; } //返回有多少只腿 public int getNumberOfLegs(){ return (numOfLegs); } public void setNumOfLegs(int numOfLegs) { if(numOfLegs!=4) { System.out.println("输入错误!"); this.numOfLegs = numOfLegs; } } //设置情绪值 public void setMood(int mood){ this.mood = mood; } public int getMood() { return mood; } //通常情况下“打招呼”的方法 public String sayHello(){ return("摇摇尾巴"); } //带情绪情况下“打招呼”的方法 public String sayHello(int mood){ this.setMood(mood); switch(this.mood){ case 1: return("呜呜叫");//如果情绪烦躁的话,就“呜呜叫” case 2: return("汪汪汪叫");//如果情绪好的话,就“汪汪汪叫” default: return("摇摇尾巴"); } } //第一只狗 无参 第一种调用时用 public Dog(){ this.mammal=true; this.carnivorous=true; this.numOfLegs=4; this.mood=1; } // 重载 有参 public Dog (boolean mammal,boolean carnivorous,int numOfLegs,int mood,String say){ this.mammal=mammal; this.carnivorous=carnivorous; this.numOfLegs=numOfLegs; this.mood=mood; } }
