Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why only one class per file [duplicate]

Tags:

java

Still coming from C++ I find it cumbersome to create many small helper classes and objects. Mostly because I have to have one file per class. I basically have a class like this:

public class mySimpleClass {
    public float[] numbers = new float[ 4 ];
}

And then I have this class:

public class myNotSoSimpleClass {
    private mySimpleClass;
    .
    .
    .
}

The second class which is not so simple is ok to have in its own file. However, the simple class is connected to the not so simple class and it would be very nice to not have to have those few lines of code in its own file.

So to sum it up, this is what one could do in C++:

public class myNotSoSimpleClass {
    private struct mySimpleClass {
        float numbers[ 4 ];
    } myStruct;
    .
    .
    .
}

Is it possible to embed/use one class inside another class, or the same file? I would just find it easier to work with large projects if I could set up these two classes into one file. Or is Java a strictly one class per file, and that's it, language?

like image 303
Espen Avatar asked Nov 10 '10 14:11

Espen


People also ask

Can you only have one class per file?

General guidelinesUsually you'll need only 1 file per type, but in some cases it's OK to have partial classes (for example, one part of the class is generated by any tool).

Can source file have more than one class?

No, while defining multiple classes in a single Java file you need to make sure that only one class among them is public.

Why can't we have more than one public class in the same file?

So the reason behind keeping one public class per source file is to actually make the compilation process faster because it enables a more efficient lookup of source and compiled files during linking (import statements).

Can you only have one class per file Java?

Yes, we can have multiple classes in same java file. But, there is one restriction over here, which is that you can have as many classes in one file but only one public class is allowed. If we try to declare 2 classes as public in the same file, the code will not compile.


2 Answers

You can have multiple classes in the same file, but only one of them can be public:

Java: Multiple class declarations in one file

like image 97
Mark Bell Avatar answered Oct 05 '22 04:10

Mark Bell


It is possible to have one class inside of another class. In Java, it's called an inner class

like image 39
Dave McClelland Avatar answered Oct 05 '22 04:10

Dave McClelland