Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is javac not complaining about more than one public class per file?

Tags:

java

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?

like image 349
Pat Avatar asked Jun 21 '11 15:06

Pat


People also ask

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

If you try to create two public classes in same file the compiler generates a compile time error.

Can we have two public classes in the same file?

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.

Can we have multiple public classes in a Java file?

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.

Can there be more than one public class per source code file?

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.


3 Answers

You cannot have more than one top level public class.

Nested/inner classes/interfaces/enums/@annotations don't count.

like image 34
Peter Lawrey Avatar answered Sep 28 '22 07:09

Peter Lawrey


In your example, InnerSample is an "inner" class. An inner class MUST be inside another class (and thus, inside the outer class' source file).

like image 39
Adam Batkin Avatar answered Sep 28 '22 05:09

Adam Batkin


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.

like image 141
Matt Ball Avatar answered Sep 28 '22 07:09

Matt Ball