Multiple Classes in One File Tutorial

Up until now, I have only included a single class inside of each .java source code file (compilation unit). In Java, you can place as many classes as you like inside of a single source code file. However, there can be only one public class per source code file and the class declaration name must match the name of the file. I haven't talked about access modifiers yet, so don't worry about the public keyword. In this tutorial, I will include two classes in the same source code file and we will compile the source code file and see what happens. This tutorial will build on concepts from my Introduction to Methods Tutorial.



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md MultipleClasses
C:\Java>cd MultipleClasses
C:\Java\MultipleClasses>Notepad MultipleClasses.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


class MultipleClasses {
    public static void main(String args[]) {
        Box small; // declare a reference variable to a Box object 
        small = new Box(); // allocate a new Box object and assign a reference to small
		
        Box medium = new Box(); // single statement - declare reference variable and allocate new Box object
        Box large = new Box();

        int smallVolume = small.calculateVolume(5, 5, 5); // invoke the calculateVolume method
        System.out.println("The volume of our small box is: " + smallVolume);

        int mediumVolume = medium.calculateVolume(10, 10, 10); // invoke the calculateVolume method
        System.out.println("The volume of our medium box is: " + mediumVolume);

        int largeVolume = large.calculateVolume(20, 20, 20); // invoke the calculateVolume method
        System.out.println("The volume of our large box is: " + largeVolume);
    }
}

class Box {

    // create a method to return the volume of the box
    int calculateVolume (int boxLength, int boxHeight, int boxWidth) {
        int returnValue; // local variable
        returnValue = boxLength * boxHeight * boxWidth;
        return returnValue;
    } 
}

Now switch back to the command prompt (CMD) and type in javac MultipleClasses.java and press Enter.
Now type in java MultipleClasses and press Enter.


C:\Java\MultipleClasses>javac MultipleClasses.java
C:\Java\MultipleClasses>java MultipleClasses
The volume of our small box is: 125
The volume of our medium box is: 1000
The volume of our large box is: 8000


Final thoughts

While it is perfectly legal to include multiple classes in each source code file, you may run into issues later down the road when it comes time to remember which file a class is in. I personally like to have one class per source code file, that way if I need to modify something in the future I can simply run a command line directory search for the file and find it instantly.


Tutorials