public int getCustomerCount() { return(customerCount); }
这是另一个"读"数据访问器方法
public int isCustomerActive() { return(customerActive); } 这是一个"写"数据访问器方法:
public void setCustomerCount(int newValue) { customerCount = newValue; } 使用访问器方法答应其它对象访问一个对象的隐藏数据而不直接涉及数据域.这就答应拥有隐含数据的对象在改变成员变量以前做正确性检查并控制成员变量是否应该被设置成新的值.
现在让我们修改例子程序来使用这些概念,如下所示.
public class HelloWorld { public static void main(String[] args) { Dog animal1 = new Dog(); Cat animal2 = new Cat(); DUCk animal3 = new Duck(); animal1.setMood(Animal.COMFORTED); System.out.println("A comforted dog says " +animal1.getHello()); animal1.setMood(Animal.SCARED); System.out.println("A scared dog says " +animal1.getHello()); System.out.println("Is a dog carnivorous? " +animal1.isCarnivorous()); System.out.println("Is a dog a mammal? " +animal1.isCarnivorous()); animal2.setMood(Animal.COMFORTED); System.out.println("A comforted cat says " +animal2.getHello()); animal2.setMood(Animal.SCARED); System.out.println("A scared cat says " +animal2.getHello()); System.out.println("Is a cat carnivorous? " +animal2.isCarnivorous()); System.out.println("Is a cat a mammal? " +animal2.isCarnivorous()); animal3.setMood(Animal.COMFORTED); System.out.println("A comforted duck says " +animal3.getHello()); animal3.setMood(Animal.SCARED); System.out.println("A scared duck says " +animal3.getHello()); System.out.println("Is a duck carnivorous? " +animal3.isCarnivorous()); System.out.println("Is a duck a mammal? " +animal3.isCarnivorous()); } }
abstract class Animal { // The two following fields are declared as public because they need to be // accessed by all clients public static final int SCARED = 1; public static final int COMFORTED = 2; // The following fields are declared as protected because they need to be // accessed only by descendant classes protected boolean mammal = false; protected boolean carnivorous = false; protected int mood = COMFORTED ; public boolean isMammal() { return(mammal); }
public boolean isCarnivorous() { return(carnivorous); }
abstract public String getHello();
public void setMood(int newValue) { mood = newValue; }
public int getMood() { return(mood); } }
interface LandAnimal { public int getNumberOfLegs(); public boolean getTailFlag(); }
interface WaterAnimal { public boolean getGillFlag(); public boolean getLaysEggs(); }
class Dog extends Animal implements LandAnimal { // The following fields are declared private because they do not need to be // access by any other classes besides this one. private int numberOfLegs = 4; private boolean tailFlag = true; // Default constructor to make sure our properties are set correctly public Dog() { mammal = true; carnivorous = true; } // methods that override superclass's implementation public String getHello() { switch (mood) { case SCARED: return("Growl"); case COMFORTED: return