Okay, so a java source file must have at least one public class and the file should be called "class-name.java". Fair enough.
Hence, if I have a class, then the following would compile:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
}
}
But what bugs me is that if I remove the 'public' access modifier from the above code, the code still compiles. I just don't get it. Removing it, the code looks like:
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
}
}
In the above code, since I removed the 'public' access modifier, my class has default or package private access, i.e. it can't be access from the outside world, only from within the package.
So my question is, how does the above code compile ? The file HelloWorld.java in this case does not have a 'public' HelloWorld class (only a package-private HelloWorld.class) and thus to my understanding should not compile.
Appreciate your time in answering my questions!
regards,
anon
解决方案
a java source file must have at least one public class and the file should be called class-name.java
Incorrect, a top level class does not have to be declared public. The JLS states;
If a top level class or interface type is not declared public, then it may be accessed only from within the package in which it is declared.