java 在类中包含别的类,为什么包含main方法的类不需要在Java中公开?

本文探讨了Java中关于类和main方法的访问限制。尽管main方法被规定必须为public,但私有类内的静态public main方法仍能正常运行。文章解释了原因,并通过示例展示了私有类如何持有并执行main方法。
摘要由CSDN通过智能技术生成

I wrote the following codeclass Hello //Note the class is not public

{

public static void main(String args[]) {

System.out.println("Hello");

}

}

So, when I run it, it runs fine and prints the output "Hello".

However, if JVM spec mandates that main method should be public since "it can't see main otherwise", shouldn't it apply to the class as well? If the JVM "can't see" Hello.main() when it is not declared public, how is it able to see the class A itself.

Is there any explanation for this other than "because the specification says so"?

And if the JVM is able to see all classes and methods as it is the "security/visibility enforcer" itself then why does the main method needs to be declared as public.

解决方案

Just for kicks, a demo that private classes can also hold main:

class Outer {

private static class Inner {

public static void main(String[] args) {

System.out.println("Hello from Inner!");

}

}

}

Compiles and runs fine from the command line:

C:\junk>javac Outer.java

C:\junk>java Outer$Inner

Hello from Inner!

C:\junk>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值