2. Java, Models and Objects

Part of CS:2820 Object Oriented Software Development Notes, Fall 2017
by Douglas W. Jones
THE UNIVERSITY OF IOWA Department of Computer Science

 

Java

We'll be programming in Java, a language many of you know, at least at a shallow level. Don't worry, we will go beyond the shallow level, but first, I want to make sure that everyone is up to speed, so we'll begin at the beginning. Here is the classic Hello World program in Java:

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World");
    }
}

It hardly seems worth the effort to add comments to such a minimal program, but we will always add a minimum of commentary to all of our programs. The bare minimum is something like the following:

// HelloWorld.java
/**
 * Program to output the text Hello World to standard output
 * @author Douglas W. Jones
 * @version 1/22/2016
 */
public class HelloWorld {
        public static void main(String[] args) {
                System.out.println("Hello, World.");
        }
}

Here, the first comment in the file is // HelloWorld.java This simply states the file name that this program is expected to occupy. Java (unlike many other programming languages) reqsuires that the file name for a source file match one of the classes defined in that source file, but that class definition may come much later in the file, after many comments, import directives, and even other class definitions. Therefore, in this class, we adopt the requirement that every source file begin with a comment giving the expected name of that source file.

The second comment is written in a special comment language called Javadoc. This is input to a program, also called Javadoc, that builds a web-site that documents Java programs. We will always write at least minimal Javadoc comments for every program we write, and as our programs grow, we will start exploring how Javadoc can help build useful roadmaps to the code we write.

Use a text editor to create this program and then run it!

Hello world is not a very interesting program. Here is a more interesting one. it prints successive members of the Fibonacci series to standard output:

// Fibonacci.java
/**
 * Program to print successive Fibonacci numbers to standard output
 * @author Douglas W. Jones
 * @version 1/22/2016
 */
public class Fibonacci {

        /**
         * Recursive function to compute a Fibonacci number
         * @param i the index of the desired Fibonacci number
         * @return the i'th Fibonacci number
         */
        private static int fib( int i ) {
                if (i < 2) return i;
                return f(i - 1) + f(i - 2);
        }

        /**
         * Main program
         * Calls fib(i) for successive values of i
         */
        public static void main(String[] args) {
                int i = 0;
                while (true) { // compute successive Fibonacci numbers
                        System.out.println( "f(" + i + ")=" + f(i) );
                        i = i + 1;
                }
        }
}

The above program is somewhat overcommented. At this point, these comments do not contribute much to understanding this code, but as the program grows, commentary at about this level of complexity will become essential.

Models:

A model is an abstraction of some aspect of reality. So, for example, we can describe a flood control reservoir by a set of variables and functions:

  • inflow(t), the inflow at time t in volume per unit time.
  • outflow(t), the outflow at time t in volume per unit time.
  • volume(t), the reservoir volume at time t.
  • level(t), the reservoir level at time t, an altitude.
  • gate-setting(t), the altitude of the edge of the sluice gate at time t.
  • f1(v) gives the level as a function of volume v.
  • f2(h) gives the outflow as a function if h, the height of the reservoir over the sluice gate.
  • The model connects these variables and functions to describe the behavior of the reservoir:

  • volume(t) = volume(t – 1) + inflow(t) – outflow(t)
  • level(t) = f1( volume(t) )
  • outflow(t) = f2( level(t) – gate-setting(t) )
  • This model is an oversimplification. It ignores groundwater, it ignores bank erosion, it ignores evaporation. All real models are oversimplifications.

    We are not interested in modelling flood control reservoirs (but the Corps of Engineers in Rock Island spends quite a bit of effort on such models). The above model is, at heart, a model of a continuous system, the kind of system that is described by differential equations. Take a numerical analysis course if you want to learn more about that kind of modeling.

    Discrete Event Models:

    In object-oriented programming, our focus will be on a different class of systems, known as discrete event systems.

    Example 1: A Highway Network

    Consider modelling a highway network. In a highway network, our model will typically have:

    roads
    Roads connect intersections, and they have attributes such as length and, travel-time. In a simple model that ignores congestion, we can ignore the possibility that the road also serves as a parking lot during rush hour.

    intersections
    Intersections tie together roads, intersections may only be occupied by one vehicle at a time, and they may have one of several different control algorithms: Uncontrolled, traffic circle, stop-signs, or traffic light. The control algorithm determines how vehicles pass through the intersection from road to road.

    vehicles
    Vehicles may either be running on a road or waiting at an intersection. Each vehicle has a plan that names a series of roads that it intends to follow to get from its current position to its destination. Vehicles may also carry cargo and passengers.

    In an object-oriented model, we can consider each of the above to be the name of a class, and each attribute of the objects in a class can be considered to be a field of that class. Some of these classes are more complex than others. Intersections have subclasses depending on the control algorithm. Vehicles may have subclasses that depend on the type (taxis and dump trucks have very different behavior).

    The events that interest us constitute another class. The following events matter in this highway network:

    Vehicle enters road
    When a vehicle enters a road, it will arrive at the intersection at the other end at a time determined by the road and (in more complex models) by the number of other vehicles on that road.

    Vehicle arrives at intersection
    When a vehicle arrives at an intersection, it will enter one of the roads leaving that intersection at a later time determined by the rules for that intersection.

    The primary attribute of every event is the time at which it occurs. In a discrete event model, each event occurs at a specific instant of time. Any process that takes time is considered to occur as a sequence of events spanning that time, where each event in that sequence marks a points where the state of the model must be checked to determine when the next event in that sequence occurs.

    Of course, if your model is being used in a context where there is a graphic display of the progress of the model, each vehicle, road and intersection will need to have display coordinates associated with it. (It would be very disorienting if display coordinates were recomputed with each event, possibly displaying roads or intersections in different locations.)

    Example 2: Digital Logic

    As a second example consider digital logic. Here, the major classes were:

    Logic gates
    A logic gate is a component that computes some logical operation such as and, nand, or, nor, or not. These should be familiar Boolean operators, although you may not be used to thinking of them as physical objects. Aside from the logical function computed by each gate, the attributes of a gate are the wires to which it connects, the current value of the output of that gate, and the time delay of that gate, from a change in one of its inputs to a change in its output.

    Wires
    Wires may be attached to the output of any logic gate to carry the value output by that gate to the inputs of zero or more other gates. The attributes of a wire are the logical value it is currently presenting to its output(s) and the time delay the wire introduces from its input to its output(s).

    Of course, if your goal is to manipulate digital logic circuits on a display screen, each gate and wire must know where it is on the display.

    Events, in a digital logic circuit, represent changes in the value of the output of a gate or the output of a wire. As in the traffic example, these output state changes are considered to be instantaneous, and for Boolean logic we use only two values, true and false. In the 1960's, the Russians built some ternary computers with the three values true, unknown and false.

    It turns out that the model just presented is just a bit too simplistic: To realistically simulate digital logic circuits containing feedback loops, you need the time delay of gates to have a small random component. Without this, as it turns out, metastable states of the feedback loops do not behave realistically. While you have no need to know this about logic circuitry, the refinement of a model to incorporate such details is very typical of real-world modelling.

    Example 3: Neural Networks

    A third example, neural networks, model the behavior of neurons in the brains of animals, including people. Note that the term neural network has another meaning, referring to classification algorithms inspired by biological neural networks. Here, we are talking about models of actual nervous systems, so the

    Neurons
    A neuron is a type of cell that fires when its membrane potential exceeds some threshold. In the absence of external stimulii, the membrane potential decreases exponentially with a fixed half-life. There are two types of external stimulii, exitatory and inhibitory. Exitatory stimulii add a fixed increment to the membrane potential. Inhibitory stimulii subtract a fixed increment (or alternatively, they increase the threshold, which reverts exponentially to its default value).

    Axons
    An axon is a part of a neuron that connects the cell body with remote connections to other neurons. The only characteristic we care about is the delay from when the cell body fires to when the synapses on that axon transmit their inhibitory or excitatory inputs to other neurons. Each synapse may have a different delay.

    Synapses
    A synapse may be either inhibitory or excitatory, and in either case, it has a strength, the amount by which it changes the membrane potential of the neuron to which it connects. The difference between inhibition and excitation can be modeled by the sign of the strength, positive for excitation, negative for inhibition.

    This is vastly oversimplified, but it is still a useful approximation for how neural networks work. This model does not cover learning, which is believed to involve modification to the synapses, and it does not cover exhaustion of the neurotransmitters when a synapse fires too frequently.