Here's my sample class, that compiles (and runs) with version 1.6.0_14 of Java:
import java.util.List;
import java.util.ArrayList;
public class Sample {
List<InnerSample> iSamples;
public Sample() {
iSamples = new ArrayList<InnerSample>();
iSamples.add(new InnerSample("foo"));
iSamples.add(new InnerSample("bar"));
}
public static void main(String[] args) {
System.out.println("Testing...");
Sample s = new Sample();
for (InnerSample i : s.iSamples) {
System.out.println(i.str);
}
}
public class InnerSample {
String str;
public InnerSample(String str) {
this.str = str;
}
}
}
I know that you're supposed to only have one public class per file in Java, but is this more of a convention than a rule?
If you try to create two public classes in same file the compiler generates a compile time error.
No, while defining multiple classes in a single Java file you need to make sure that only one class among them is public. If you have more than one public classes a single file a compile-time error will be generated.
A single Java program can contain more than one class and there are no restrictions on the number of classes that can be present in one Java program.
Each source file should contain only one public class and the name of that public class should be similar to the name of the source file. If you are declaring a main method in your source file then main should lie in that public class.
You cannot have more than one top level public class.
Nested/inner classes/interfaces/enums/@annotations don't count.
In your example, InnerSample
is an "inner" class. An inner class MUST be inside another class (and thus, inside the outer class' source file).
You're not allowed to have more than one top-level class per file. InnerSample
is an inner class.
This is an example of what is prohibited in a single file:
public class Sample {
}
public class Sample2 {
}
See JLS §7.6.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With