Szmagpie Szmagpie - 3 months ago 6x
Java Question

Do different classes need to be in different java files?

I am fairly new to Java, and whenever we have written programs in school, we put each class in a separate java file, but I do not remember why this was (if there was even a reason). Right now I am going back over my notes and trying to "understand" how it all works.

Is this necessary to do, and why? Moreover, is there a distinction about where the files should be stored—e.g. in the same directory?

E.g. if we have a class 'Vehicle' and a class 'Car' extending 'Vehicle', do we need to save 'Vehicle' and 'Car' in java files '' and '', respectively, or could both classes be saved in (say) ''?

Duplication disclaimer: my question differs from this one, as mine asks whether it is possible to put multiple classes in one .java file; I am specifically interested in the explanation, i.e. why it is/not possible. I am not interested in what the method is called (the linked question just says 'it is necessary, now what is it called?'): my question is more basic than this.


It's possible to place multiple classes in one .java file. However, this is a bad idea. Here's why:


public class Foo { }

public class Bar { }

A source file that contains the above code as-is won't compile, as each .java file can contain only one public class/interface/enum (btw, these are called "type"s). As a result you have to do this to keep them in the same file:


public class Foo { }

class Bar { } // Not public

Or this:


class Foo { } // Not public

public class Bar { }

Now here comes the drawback: If the non-public type(s) contain something useful to everything (such as a method for generating random numbers over a normal distribution), it won't be accessible to anything that is not in the package called!

Besides, it's easier to manage small source files.

Moreover, is there a distinction about where the files should be stored—e.g. in the same directory

Yes - this depends on the package names. For example, the packages, foo.baz, foo.qux,, bar.baz and bar.qux would look like these subfolders of a common source folder (let's call it src):

L___ ./src/foo/
|    L__ ./src/foo/bar/
|    L__ ./src/foo/baz/
|    L__ ./src/foo/qux/
L___ ./src/bar/
|    L__ ./src/bar/foo/
|    L__ ./src/bar/baz/
|    L__ ./src/bar/qux/

When you apply this logic to java.lang.Object (assuming the source folder is still called src), you'd get this:

L___ ./src/java/
|    L___ ./src/java/lang/
|    |    L___ ./src/java/lang/