/** * Models ants living in a 1-dimensional world.
* A queen ant can make a bunch of ants and spread them around in a * 1-dimensional world. An ant from a particular colony can always calculate * its distance from its queen. An ant can also move its queen to a different * location. Wherever the queen moves to, her ants always know how their * relative distance from her.
* The above is modeled by a Queen class with an abstract * Ant inner class. * The Ant inner objects has direct access to the location of its * outer Queen object. * @author S.B. Wong * @author D.X. Nguyen */ public class Queen { private int origin; // what does it mean for origin to be static? /** * Is part of a Queen instance, just like the * origin field and the makeAnt() method are * parts of a Queen instance. */ public abstract class Ant { public abstract int calcDist(); public void moveQueen(int origin) { Queen.this.origin = origin; } } public Queen(int origin) { this.origin = origin; } /** * Factory method: relegate the task of manufacturing concrete Ant objects * to the Queen object because the Queen object intrinsically "knows" how * to make its inner objects. */ public Ant makeAnt(final int loc){ return new Ant() { // Anonymously created Ant object public int calcDist(){ // overriding calcDist. As long as this return loc - origin; // object is alive, the value of loc } // stays with it and does not change. }; } } /** * Test class for used with DrJava.
 // After compiling, enter the following in the interactions window.
 TestQueen.vicAnt1.calcDist()
 TestQueen.vicAnt2.calcDist()
 TestQueen.lizAnt1.calcDist()
 TestQueen.lizAnt2.calcDist()

 // Now move the queens around:
 TestQueen.lizAnt2.moveQueen(0)
 TestQueen.vicAnt1.moveQueen(-1)

 // Check the distance again:
 TestQueen.vicAnt1.calcDist()
 TestQueen.vicAnt2.calcDist()
 TestQueen.lizAnt1.calcDist()
 TestQueen.lizAnt2.calcDist()
 
*/ class TestQueen{ public static Queen vicky = new Queen(10); public static Queen lizzy = new Queen(-10); public static Queen.Ant vicAnt1 = vicky.makeAnt(5); public static Queen.Ant vicAnt2 = vicky.makeAnt(-7); public static Queen.Ant lizAnt1 = lizzy.makeAnt(-6); public static Queen.Ant lizAnt2 = lizzy.makeAnt(2); }