CIT 591 Solving "static context" problems
Fall 2004, David Matuszek

Many of you are running into "static context" problems in the Hammurabi assignment. Here are three approaches to solving the problems.


If you put everything in the main method

Since we haven't really covered methods yet, this is what I expected you to do. In this case, the solution is very simple: Declare all your variables in the main method. Like so:

class Hammurabi {
    public static void main(String[] args) {
        int population = 100;
        int grainInStorage = 2800;
        etc.
    }
}

The advantages of this solution are (1) it's simple, and (2) you don't have to know anything about static variables and methods. It has the disadvantage that large monolithic programs like this are harder to read, understand, and debug.


If you create your own methods

Best solution:

This solution is the best because it is good style to use lots of simple methods, rather than one big monolithic program.

A workable (but ugly) solution:

Make all your variables, and all your methods, static.

class Hammurabi {
    static int population = 100;
    static int grainInStorage = 2800;
    etc.

    static void displaySummary() { ... }

    etc.
}
Every time you get a complaint about a non-static variable or method in a static context, just make it static. This solution has the advantage that it does work, and the disadvantages that (1) it's ugly, (2) it's an annoying nuisance, and (e) it's not object-oriented.