/* SimpleExample/Ant.java A very simple class, with four fields: ID weight x, y */ import java.util.Random; // Only the Random class public class Ant { // class variables ("static") -- one copy in Ant class object itself static int nextID = 0; // next ID to assign to ants static Random rng; // pointer to rng given to us // instance variables int ID; // these have the default access double weight; // "package private" int x, y; // see Access controls in java books // constructors Ant () { // create with defaults provided ID = nextID++; weight = 0.0; x = 0; y = 0; } Ant ( int X, int Y, double wt ) { // constructor with parameters ID = nextID++; weight = wt; x = X; // note case matters! x != X y = Y; } ////////////////////////////////////////////////////////////////////////////// // doSomething -- silly method... public double doSomething ( int i ) { double returnVal = 0; double d = 20; // i'd recommend better names than this!! // Here we send the printf message to the PrintStream object referenced by // the "out" field of the System class! See System in Java API, // and see the printf method of the PrintStream class for details // on formatting the output. (Its bascially following c printf rules.) System.out.printf( "Ant ID=%d (wt=%.2f) sent doSomething():\n", ID, weight ); if ( ID % 2 == 0 && weight > 10.0 ) returnVal = (weight + i) / d; else returnVal = getUniformRandomFractionOf( weight ); // send to "this" object System.out.printf( " <-- %.3f = returnValue\n", returnVal ); return returnVal; } // getUniformRandomFractionOf // returns a random fraction of the parameter sent to in public double getUniformRandomFractionOf ( double d ) { System.out.printf( " - Ant ID=%d sent getUniformRandomFractionOf( %.3f ):", ID, d ); double rvalue; // lets send a msg to whatever the variable "rng" points to, // in this case, to an instance of the Java Random class we created in Main! double r = rng.nextDouble(); System.out.printf( " -> r = %.5f\n", r ); rvalue = r * d; return rvalue; } public void printSelf () { System.out.printf( "ID = %d, x=%d, y=%d, weight = %.2f\n", ID, x, y, weight ); } ///////////////////////////////////////////////////////////////////////////////// // accessors (getters/setters) public static void setRng ( Random r ) { // for the class variable! rng = r; } public int getID () { return ID; } public double getWeight () { return weight; } public void setWeight ( double wt ) { weight = wt; } // NB -- no set/get-X or -Y !! }