为什么Java中的main方法总是需要公开? [英] why main method in Java need to be public always?

查看:115
本文介绍了为什么Java中的main方法总是需要公开?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么java中的main方法总是需要公开?如果我们将具有main方法的类声明为默认值,它将成功执行它,但如果我们将main方法声明为默认值,那么JVM将抛出错误。为什么?
这里

Why main method in java need to be public always? If we declare the class having main method as default it will execute it successfully but if we declare main method as default, then JVM will throw error. Why? Here

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来公开。但是,如果我们不将其声明为公开,则会产生错误。

推荐答案

static 以便JVM可以运行该方法而无需实例化类对象
+ public 以便JVM可以在没有任何访问问题的情况下自由访问它。

static so that the JVM can run the method without having to instantiate the class object + public so that the JVM can access it freely without any access issues.

这篇关于为什么Java中的main方法总是需要公开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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