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?
You’re not allowed to have more than one top-level class per file.
InnerSampleis an inner class.This is an example of what is prohibited in a single file:
See JLS §7.6.