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