没有公共类的.java文件的Java编译 [英] Java compilation of a .java file without a public class

查看:151
本文介绍了没有公共类的.java文件的Java编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以java源文件必须至少有一个公共类,该文件应该被称为class-name.java。很公平。

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.
    }
}

在上面的代码中,我删除了'public '访问修饰符,我的类有默认或包私有访问,即它不能从外部访问,只能从包内。

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.

所以我的问题是,上面的代码如何编译?在这种情况下,文件HelloWorld.java没有'公共'HelloWorld类(只有一个包私有的HelloWorld.class),因此我的理解不应该编译。

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!

问候,
anon

regards, anon

推荐答案


一个java源文件必须至少有一个公共类,该文件应该被称为class-name.java

a java source file must have at least one public class and the file should be called class-name.java

不正确,顶级类不必声明为public。 JLS声明;

Incorrect, a top level class does not have to be declared public. The JLS states;


如果顶级类或接口类型未声明为public,则只能从包中访问它宣布它。

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.

参见 http://java.sun.com/docs/books/jls/second_edition/html/names.doc.html#104285 第6.6.1节。

这篇关于没有公共类的.java文件的Java编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆