简体   繁体   English

运行Java程序的NetBeans,其main为非公共类

[英]NetBeans running Java program with main in non-public class

I know that there were plenty of questions like this, but in all of them, the answers were " you cannot run a Java program with main method in a non-public class ". 我知道有很多这样的问题,但是在所有这些问题中,答案都是“ 不能在非公共类中使用主方法运行Java程序 ”。 ( What if main method is inside "non public class" of java file? ) 如果主要方法在java文件的“非公共类”内部怎么办?

However, I tried such a situation in NetBeans, and it ran perfectly fine. 但是,我在NetBeans中尝试过这种情况,并且运行得很好。 Why? 为什么?

Is having a main in a public class a convention or a strict rule ? 是具有在一个公共类主要 公约严格的规定

The rule is the following 规则如下

The method main must be declared public , static , and void . 方法main必须声明为publicstaticvoid It must specify a formal parameter (§8.4.1) whose declared type is array of String . 它必须指定一个声明的类型为String数组的形式参数(第8.4.1节)。

There is however no restriction on the accessibility of the enclosing class. 但是,对封闭类的可访问性没有限制。 Note however that top level classes cannot be private or protected . 但是请注意,顶级类不能为privateprotected Maybe that's where your confusion arises. 也许那是您困惑的地方。

You can very well have 你可以很好地拥有

class Example {
    private static class Other {
        public static void main(String[] args) throws Exception {
            System.out.println("main in Other");
        }
    }
}

and execute 并执行

> java Example$Other

That would show 那会表明

main in Other

I don't know why you would , but you can . 我不知道为什么你的,但你可以

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

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