简体   繁体   English

在Java中访问没有顶级类的非顶级类

[英]Accessing non top-level class without a top level class in Java

I have a Java file TestThis.java like the following: 我有一个Java文件TestThis.java ,如下所示:

class A
{
    public void foo() 
    {
        System.out.println("Executing foo");
    }
}

class B
{
    public void bar()
    {
        System.out.println("Executing bar");
    }
}

The above code file is compiling fine without any warnings/errors. 上面的代码文件编译正常,没有任何警告/错误。 Is there any way I could access any of class A or B without a top level class from any other external class? 没有任何其他外部类的顶级类,是否可以通过任何方式访问A类或B类?

If no then why does Java even permit compiling of such files without a top-level class? 如果不是,那为什么Java甚至允许在没有顶级类的情况下编译此类文件?

As usual (for example, accessing from the Test.java): 和往常一样(例如,从Test.java访问):

public class Test {
    public static void main(String... args) {
        A a = new A();
        a.foo();
        B b = new B();
        b.bar();
    }
}

The rule here is that you could not have more than one public class in the source file. 这里的规则是,源文件中不能有多个公共类。 If you have one, the filename must match this public class name. 如果您有一个文件名,则文件名必须与此公共类名匹配。 Otherwise (your case), you can name your file as you wish. 否则(根据您的情况),您可以根据需要命名文件。 Other, non-public classes, will be package-visible and you can access them as usual. 其他非公共类将对程序包可见,您可以照常访问它们。

Any other class in the same package can access A and B; 同一包中的任何其他类都可以访问A和B; in this case the null package is being used since no package statement is present for the source file. 在这种情况下,由于没有源文件的package语句,因此使用了空包。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM