Java Article 13 - Using Mulitple Classes Part 1

In this article we will cover one of the really cool things you can do in object oriented programming(OOP): Dividing up your program into multiple classes.

In today's example we have a program that does a simple calculation using two separate classes. The program has a main class with a main method. The main method is where Java begins execution. This is sometimes referred to an entry point. Java textbooks also call this the Driver Class since it drives execution.

In my experience, the term Driver Class is not widely used outside of some textbooks. It is not the best use of terminology because people may confuse it with things like class drivers or device drivers.

The second class, AreaCalculator, will be what is sometimes called an external class. This is a separate class the main class asks (calls) to do some work.

So in the example below the main class, which we named MainClass, has the main() method which instantiates an object from our external class, AreaCalculator.

In general terms you need to create two classes in the same folder. The specifics on how you create two classes depends on what kind of editor or IDE you are using. If you are using an editor you probably want to create two .java files. In Eclipse you create two classes in the same package.

First create a class named MainClass and use this code:

public class MainClass 
	public static void main(String[] args) 
		int outputToConsole;
		AreaCalculator areaCalc = new AreaCalculator();
		//Example 1
		 // Here we assign our variable to the return value of
		 // ourObject.calculateRectagleArea(5, 5);
		outputToConsole = areaCalc.calculateRectagleArea(4, 5);
		//Example 2
		//Here is another way you can do the same thing:
		System.out.println(areaCalc.calculateRectagleArea(9, 10));
		 // Doing it this way does not require you to use a variable
		 // This works because calculateRectagleArea returns its
		 // area value, then that area value is plugged directly into
		 // the System.out.println() statement.
		 // Sometimes you will want to use example 1 because you
		 // may want to store outputToConsole for use later on.

Now create a new class in the same directory or folder, and name it AreaCalculator. You now will have two classes. By default java only looks in the same folder for other classes you call, unless you tell it differently.

This code goes into your AreaCalculator class:

public class AreaCalculator 
	 // See word "int" below? That specifies that the return 
	 // type will be an int. "void" is used if there is no value
	 // returned.	
	public int calculateRectagleArea(int length, int width)
		 // The two ints above, length and width, are properties. 
		 // They are sent from MainClass. We plug these two properties
		 // into the statement below, and do a calculation:
		int area = length * width;
		//This returns the int area to the class that called it.
		return area;

What this example shows is a simple example of modularity and reusability. AreaCalculator is modular and reusable since you could take this class and copy it into another program where you need the area of a rectangle calculated. This OOP feature is designed to save you time in that you can have modular classes you can reuse anywhere you need them.

In a team environment, multiple programmers may instantiate and use AreaCalculator objects from the class you wrote, or even use the same object you instantiated.

The object you instantiate from AreaCalculator has a simple job: it takes a couple of arguments (length and width) multiplies them, then returns the multiplied value.

Before any communication or calculations occur you need to instantiate your AreaCalculator object so it can do the work. Here the AreaCalculator class is just a blueprint for an object and doesn't do anything on its own. MainClass instantiates a new object from AreaCalculator with:

AreaCalculator areaCalc = new AreaCalculator();

We could call this object anything we like but here we use the name areaCalc. It is good to have object names that make some kind of sense. Often programmers just use a camel case version of the class name, such as areaCalculator. Some people prefix the class name with "my" so you would have "myAreaCalculator." Some even shorten it to one letter such as just an "a" for an object name. I don't recommend using one letter object names because it is more difficult to determine what "a" is vs. "areaCalculator" is.

One key thing in this example is how the main class and the object communicate.

After the areaCalc object is created (instantiated) we can then talk to it and tell it to execute one of its methods. This is called "calling a method." The syntax is the same for calling a method within a class except you have to provide the object name. It looks like this:

objectName.methodToBeCalled(arguments to be sent to the method);

In today's example it looks like:

areaCalc.calculateRectagleArea(4, 5);

Here we tell areaCalc to execute its calculateRectagleArea method the and we send it the length and width of the rectangle as arguments as seen with the "(4, 5)" notion.

Java then looks for the object areaCalculator, and takes these two numbers and plugs them into the two corresponding parameters in the object's method:

public int calculateRectagleArea(int length, int width)
	//do calculations
	int area = length * width;
	return area;

In the object's calculateRectagleArea method we have to specify the type of the data being received (the received arguments or the parameters). Here they are both int so we have to specify them as int's.

The parameters length and width can then be used in the statement:

int area = length * width;

Finally we return area to the statement in out main class that called this method with:

return area;

So now the calling statement:

outputToConsole = areaCalc.calculateRectagleArea(4, 5);


outputToConsole = 20;

Since area in this case was = 20.

Using multiple classes is another way to use encapsulation. It can be used to hide (encapsulate) the code in one class from other classes. This becomes very useful in larger programs, with multiple programmers, where you may not want other programmers to accidentally use or change your methods and variables.

Using multiple classes is also a way of organizing or structuring your code. You could group related variables and functions into different classes and model them after real life objects. Here we put our area calculation code into a separate class from our main class. If we wanted to we could add more classes each performing their own calculations.

A big benefit of using multiple classes is modularity and reusability. It is modular in the sense that it is a self-contained unit, in this case a class file. It is reusable in that if I decided to make a new program somewhere that needed to calculate the area of a rectangle I could just copy my AreaCalculator class to this new project and now I would have pre-written and functional code to support the use of area calculation.

How handy is that?

Modular and reusable code saves time during the software development process, and allows you to be more productive. Encapsulation not only saves time, which prevents bugs that take time to fix, but it also improves product quality by preventing bugs from slipping into released software products.

In part two we will use a more complex example, and cover initializing your new objects to make them unique.