5

File name: B.java

public class B
{
    public static void main(String[] args){}
}
public class A{}
  • java B.java runs without error
  • javac B.java gives a compile error: class A needs to be declared in a file A.java

I understand that a java file can not have more than one public class, but why can a java file run without error using the java command when you get compile errors for the code using javac?

0

2 Answers 2

8

Java-11+ allows launching Single-File Source-Code programs without compiling. You can learn more about it from this article. As per the specification, if the first class in the file has main, it executes the same without caring for other public classes in the file. Thus, if you change the order of classes in the file and try java B.java, it will fail.

Sign up to request clarification or add additional context in comments.

Comments

1

My guess, and it is only a guess since I haven't used Java 11 extensively, is that:

  • The "javac" command produces class files that can be combined into a large program, and thus there could be multiple references to class A "elsewhere" in the program. It is this generality that produces the restriction on one public class per source file (though frankly I don't see why compiling B.java cannot result in A.class and B.class)

  • The "java" command processes a single source file. From that point of view it is irrelevant whether A is public or not; A can be used from within the single file (same package!) in any case.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.