Incremental Java
Java File

Making A Java File

Imagine you are a composer. This is the modern age, so you can write music using a program that lets you type in notes, and even hear how it sounds.

If you had to compose music this way, you'd discover there's more to writing music than writing music. In particular, you'd have to understand how to use the music software. You'd have to know how to retrieve songs from files, how to organize the music, how to print it, how to burn the contents to a CD. These are all technical skills you'd have to have, which aren't even related to the skill of composing the song in the first place.

Programming in Java is very much like that. You don't write programs on a piece of paper. (You could, write it down, but eventually, you'd have to type it into a computer). You need to type the program, on a computer.

Writing a program requires you to edit a file. If you've used computers (and I'm assuming you've used them, even if you've never programmed), you know that computers store files, and that files have names.

Java has an unusual requirement. It requires that you give the file the same name as the class, plus a .java extension. For example, if the class name was Foo, the file has to be named Foo.java.

More Than One Class in a File?

What happens if you had two classes in a file? What would you name the file?

Java doesn't really allow more than one class per file. I mean, technically, you can do it. Java says there is only one public class per file. The rest of the classes have to be private. I won't go into an explanation of public or private now, suffice it to say that private means the classes are used internally within the file, and other classes can't use them. (There's also inner classes and anonymous classes, but I really don't want to talk about that now).

For now, just assume you can only put one class per file. That's how most people program in Java, anyway.

Other Languages

Java is perhaps the only language that makes you name the file the same name as the class in the file. Other languages like C, C++, don't have this requirement. It has one big advantage. It's easy to find the class by looking at the name of the file.