Java compilation of a .java file without a public class

后端 未结 6 2003
被撕碎了的回忆
被撕碎了的回忆 2020-12-19 06:01

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, th

相关标签:
6条回答
  • 2020-12-19 06:04

    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.

    See http://java.sun.com/docs/books/jls/second_edition/html/names.doc.html#104285 section 6.6.1.

    0 讨论(0)
  • 2020-12-19 06:06

    A main method is just like any other method. The only difference is that it may be invoked from the command line with the java command. Even if the main method is not visible from the command line, the class can still be used like any other Java class, and your main method may be invoked by another class in the same package. Therefore i makes sense that it compiles.

    In Java main function are not special in any sense. There just exists a terminal command that is able to invoke static methods called main...

    0 讨论(0)
  • 2020-12-19 06:06

    When you do not specify the access modifier of the class (or its field or method), it is assigned "default" access. This means it is only accessible from within the same package (in this case, the default package).

    The website Javabeginner.com has an article on the subject - you should become familiar with access modifiers in Java, either from this site, or others.

    0 讨论(0)
  • 2020-12-19 06:10

    that´s nothing to wonder about. I suppose this behavior is similar to the one of some C/C++-compiler.

    Code like "void main() { /.../ }" will be compiled correctly by those compilers, although it is not standards-compliant code. Simply said, the compiler exchanges the "void" with "int".

    I think a similar behavior is implemented by the java compiler.

    Regards, xong

    0 讨论(0)
  • 2020-12-19 06:14

    You can place non-public class in a file, and it's not a bug but feature.

    Your problem is on level of packaging, not compile. Because you can compile this file with non-public class, but you can't call it from outside, so it's not working as application base class

    Like this:

    // [+] single file: SomeWrapper.java 
    
    public class SomeWrapper {
        ArrayList<_PrivateDataType> pdt;
    }
    // [-] single file: SomeWrapper.java 
    
    // [+] single file: _PrivateDataType.java 
    class _PrivateDataType {
        // members, functions, whatever goes here
    }
    
    // [-] single file: _PrivateDataType.java 
    
    0 讨论(0)
  • 2020-12-19 06:23

    There are valid usages for a non public classes. So the compiler does not give error when you try to compile the file.

    0 讨论(0)
提交回复
热议问题