/* --- CSU213 Fall 2006 Lecture Notes --------- Copyright 2006 Viera K. Proulx Lecture 14: October 5, 2006 Privacy of Constructors: Assuring Integrity of Data (Runs in Java 1.5) */ class Rat{ int life; // Rat always starts its life with five ticks to go public Rat(){ this.life = 5; } // Rat can change its life expectancy only by eating or starving private Rat(int life){ this.life = life; } // a day goes by, the rat starves public Rat starve(){ return new Rat(this.life - 1); } // rat found some food public Rat eat(int foodsize){ return new Rat(this.life + foodsize); } // is the rat dead? public boolean isDead(){ return this.life <= 0; } // is this the same rat as the given rat? public boolean sameRat(Rat that){ return this.life == that.life; } public static void main(String argv[]){ Rat rattie = new Rat(); boolean testStarve = rattie.starve().sameRat(new Rat(4)); boolean testEat = rattie.eat(3).sameRat(new Rat(8)); boolean testIsDeadno = rattie.isDead() == false; boolean testIsDeadyes = (new Rat(0)).isDead() == true; System.out.println("Test the method starve:" + testStarve + "\n" + "Test the method eat:" + testEat + "\n" + "Test the method isDead (no):" + testIsDeadno + "\n" + "Test the method isDead (yes):" + testIsDeadyes); } }