Two Laptop Bag
The moose likes Beginning Java and the fly likes multiple classes - back to basics Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "multiple classes - back to basics" Watch "multiple classes - back to basics" New topic

multiple classes - back to basics

Matt Fielder
Ranch Hand

Joined: Oct 27, 2004
Posts: 158
for some reason my little brain is having a problem grabbing something right now.

EXCEPT NESTED CLASSES, how can you have multiple classes in the same file? Many examples I've seen have multiple classes written into the same program. Why wouldn't you (for the sake of true OOP) put each of these in its own file? Is it merely for the simplicity of the example so that someone could just copy it and run it for themselves?? Why wouldn't you limit each program to one class to contain its objects and methods? It just seems cleaner.

Also, I just read in Eckel's book (Thinking in Java - that if you have many classes in one file you will end up with many *.class files when you compile from one *.java file. So if I load my single .java up with several class declarations, it'll produce multiple .class files?

First, is this true?
Second, doesn't that tend to ruin access levels set by the designer?
Jeff Bosch
Ranch Hand

Joined: Jul 30, 2003
Posts: 805
You can have as many classes in a file as you want in Java, but you can only have one public class in the file. You usually group them in a file if the other classes are "helper" classes for the public class.

Yes, when you compile you will get a separate $class file for each class in the program, no matter how many physical files hold them.

This structure has no effect on the access levels. How the class is declared controls how the class is accessed.

Give a man a fish, he'll eat for one day. Teach a man to fish, he'll drink all your beer.
Cheers, Jeff (SCJP 1.4, SCJD in progress, if you can call that progress...)
Nathaniel Stoddard
Ranch Hand

Joined: May 29, 2003
Posts: 1258
No matter where you put your class definitions, you'll have separate class files. We see this obviously with the pretty "$" in class files for nested class definitions.

As for the first part of your question, technically, the compiler is supposed to enforce the fact that only one public class can be in each file. And yes, I would always create a new file for each class, but that's just me. Unless it's a nested class, it gets its own very own file -- just my way of telling the class that it's important to me.

I agree. Here's the link:
subject: multiple classes - back to basics
It's not a secret anymore!