OO Programming in Java

Class 1 Material


Zoo Example



Problem Statement

Write a computer program to help determine how many shoes must be ordered for all the animals in a zoo.One size fits all.







Code



View

import java.lang.*;
import java.util.*;
import java.awt.*;

public class View extends Frame implements Observer {

    private Zoo zoo_;
    public Zoo zoo() { return zoo_; }
    public void zoo(Zoo aZoo) {zoo_ = aZoo; }

    public static void main(String args[]){
        View theView = new View();

        theView.zoo().computeFootCount();

        (new Frame()).show();
    }

    View() {
        this.initialize();
    }

    private void initialize() {
        this.zoo(new Zoo());
        this.zoo().addObserver(this);
    }

    public void update(Observable obs, Object o) {
        String theString = (String) o;
        System.out.println(">> " + theString);
    }

}


Zoo

import java.util.*;
import java.lang.*;

class Zoo extends Observable {

    private String name_;
    public String name() { return name_; }
    public void name(String aName) {name_ = aName; }

    private Vector animals_;
    public Vector animals() { return animals_; }
    public void animals(Vector theAnimals) { animals_ = theAnimals; }

    Zoo() {
        this.initialize();
    }

    private void initialize() {
        this.animals(new Vector());
        this.name("Fred's Zoo");

        Vector theAs  = this.animals();
        theAs.addElement(new Animal("George", 2));
        theAs.addElement(new Animal("Centi",  43));
        theAs.addElement(new Animal("Wormy",  0));
        theAs.addElement(new Animal("Yogi",   4));

    }

    public void publicize(String aString) {
        this.setChanged();
        this.notifyObservers(aString);
    }

    public int computeFootCount() {
        int totalFootCount = 0;
        Enumeration theAnimals = this.animals().elements();
        while (theAnimals.hasMoreElements()) {
            Animal anAnimal = (Animal) theAnimals.nextElement();
            totalFootCount = totalFootCount +
                                anAnimal.footCount();
        }
        this.publicize("Shoes to order = " + totalFootCount);
        return totalFootCount;
    }
}

Animal

import java.util.*;
import java.lang.*;

class Animal {

    private String name_;
    public String name() { return name_; }
    public void name(String aName) {name_ = aName; }

    private int footCount_;
    public int footCount() { return footCount_; }
    public void footCount(int theFootCount) { footCount_ = theFootCount; }

    Animal() {
        this.initialize();
    }

    Animal(String aName, int feet) {
        this();
        this.name(aName);
        this.footCount(feet);
    }

    private void initialize() {
        this.name("John Doe");
        this.footCount(0);
    }

}