Home CPSC 220

Programming with Objects

Multiple File Programs

While we can put multiple classes in one file, the normal way of programming in Java is to put each class into its own file. This is very helpful with bigger projects as it keeps the files from being very large, and makes it easier to work with others.

To do this in NetBeans, you can choose the "New File" option, choose "Java Class" as the type, and pick the name. Just like for the class containing main, the name of the class must match the name of the file.

How can we move the "Circle" class into its own file?


Enumerations are another way of creating data types in Java. Rather than listing all of the attributes belonging to that type, as in a class, an enumeration lists all of the possible values for a type. For example, if we need cardinal directions in a program:

enum Direction {

Creates a type called "Directions" which can take on any of the four values enumerated above:

Direction dir = Direction.North;

Enumerations can also be used in switch statements:

switch (dir) {
    case North:
    case South:
    case East:
    case West:

Using enumerations makes code more readable than "magic numbers", such as using 1 for North, 2 for South and so on.

Designing Programs with Objects

Now we have two ways of splitting up programs: functions and objects. When we go to write a program, we now have even more options of how to break it up.

One way to do this is to look for "nouns" and "verbs" in our program. Nouns can then be objects and verbs can be functions.

We can then think about each object and think of what properties it needs, and make them member variables. We can also think about what behaviors the objects should have and make them into member functions.

Example: War!

Here is a link to the War game which we developed. For convenience, all the classes are together in one file.

Copyright © 2018 Ian Finlayson | Licensed under a Creative Commons Attribution 4.0 International License.