/** * Zoo.java * * A short java example, showing : * - objects, their fields (i.e. data), constructors, and methods * - object inheritence ("extends" in java) * - "generics" notation (i.e. Vector) * - "static" method (i.e. Zoo.main() class); *not* invoked on instance * - main() is required entry for application executable class * - import of a java language library * - iterator looping syntax, i.e. "for (Vector i: myVector){ foo(i) }" * * Some awkward bits : * - can't use standard container (Vector) without import * - not easy to make "woof woof woof" * - not easy to instantiate objects dynamically (i.e. from list) * - can't use [0] subscripts on Vector * - ... but built-in arrays with have fixed lengths. * * Using it : * $ javac Zoo.java * $ java Zoo * The animals in the zoo say * meow * meow * woof * woof woof woof * * Generating docs: * $ mkdir docs * $ javadoc *.java -d docs * ... but this is only works if classes area declared public * ... and that requires each class be in its own file ClassName.java * ... (Oh Java.) * * Packaging the .class files (or .class and .java) files : * $ jar cfe zoo.jar Zoo *.class (or *) * * @see http://cs.marlboro.edu/courses/spring2012/programming/code/java/jims_java_demo/README.txt * @author Jim Mahoney * @since 2012-04-06 */ import java.util.Vector; /** * an animal and its characteristic noise */ class Animal { String noise; // instance data Animal(){ // instance constructor, sets data noise = ""; } /** * @return what the animal says */ public String says(){ // instance method, uses data return noise; } } class Cat extends Animal { // class inheritence Cat(){ noise = "meow"; } } class Dog extends Animal { Dog(){ noise = "woof"; } Dog(int nWoofs){ // another constructor (different args) noise = ""; for (int i = 0; i < nWoofs; i++){ noise = noise + "woof "; } } } /** * a collection of animals with barnyard noise printing */ class Zoo { Vector animals = new Vector(); // java "generics" void add(Animal who) { animals.add(who); } static void println(String message){ System.out.println(message); } void printNoises(){ println("The animals in the zoo say"); for (Animal who : animals){ println(who.says()); } } public static void main(String[] args) { Zoo z = new Zoo(); for (int i = 0; i < 2 ; i++){ z.add(new Cat()); } z.add(new Dog()); z.add(new Dog(3)); z.printNoises(); println(""); println("The first animal says '" + z.animals.get(0).says() + "'"); println("The last says '" + z.animals.lastElement().says() + "'"); } }