为什么main方法不能在默认范围内? [英] why main method can't be of default scope?

查看:70
本文介绍了为什么main方法不能在默认范围内?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们使用默认范围(非公共)和公共main方法声明该类,则该类将成功执行.这里的类作用域比主方法作用域严格.

If we declare the class with default scope(non-public) and public main method it executes successfully. Here class scope is mote stricter than main method scope.

但是,如果我们将main方法声明为默认方法,那么JVM将引发错误.为什么?

But if we declare main method as default, then JVM will throw error. Why?

class DefaultTest {
    public static void main(String[] args) {
        System.out.println("output.........");
    }
}

运行成功,但是

class DefaultTest {
    static void main(String[] args) {
        System.out.println("output.........");
    }
}

这不会.

我的意思是,如果类本身不是公共的,JVM仍然可以访问main方法,这意味着不需要main是公共的.但是,如果我们不将其声明为公开,则会引发错误.

推荐答案

它由Java语言规范指定,请参见

It is specified by the Java Language Specification, see http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html chapter 12.1.4. Invoke Test.main:

方法main必须声明为public,static和void.

The method main must be declared public, static, and void.

JVM规范也需要它,请参阅@ A4L的答案.

It is also required by the JVM specification, see the answer from @A4L.

这篇关于为什么main方法不能在默认范围内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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