Why doesn't javac complain about more than one public class per file?

Here is my sample class that compiles (and runs) with Java version 1.6.0_14:

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 should have only one public class for each file in Java, but is this more a convention than a rule?

+5
source share
4 answers

You are not allowed to have more than one top-level class for each file. InnerSampleis an inner class.

This is an example of what is prohibited in a single file:

public class Sample {

}

public class Sample2 {

}

See JLS & sect; 7.6 .

+12
source

You cannot have more than one top-level public class.

/ ///@ .

+4

In your example InnerSample, this is the inner class . The inner class MUST be inside another class (and therefore inside the source file of the outer class).

+1
source

Because it's an inner public class

0
source

All Articles