私有静态方法 class

Static Methods in Private class

我最近开始学习 java 我的第一个 OOP language.I 读到 static methods 不需要 class 来实例化它们 运行 当你将 class 喂给 JVM 时。我的问题是如果 static methodprivate nested class 内会发生什么。还会运行吗?

编辑-我试过它不起作用,我想知道后台发生了什么。

public class tester{
private class estupid{
    public static void main(String[] args){
        System.out.println("Hello Im a static method of a private class and main too");
    }
}
}

对于投反对票的人,一个更有效的建议 activity 会告诉该片段有什么问题,谢谢。

main 方法必须是 publicclass 的成员。静态方法是 class 本身的子方法,而不是对象,或者是 class.

的 "instance"

错误较多,直接编译代码即可。我建议你使用命令行 javac 编译

  1. 如果你按原样编译代码

    C:\src>javac tester.java
    tester.java:3: error: Illegal static declaration in inner class tester.estupid
                    public static void main(String[] args) {
                                       ^
      modifier 'static' is only allowed in constant variable declarations
    1 error
    
  2. 根据上述错误,将嵌套 class 设置为静态嵌套 class。现在代码将成功编译,但在 运行 编译它时会出现错误:

    C:\src>javac tester.java
    
    C:\src>java tester
    Error: Main method not found in class tester, please define the main method as:
       public static void main(String[] args)
    or a JavaFX application class must extend javafx.application.Application
    
  3. 有了上面的错误你可以理解你是运行ning tester class,但是它不包含任何JVM搜索的main方法。所以在 tester class 中添加一个 main 方法,是的,你可以在 static inner class 中调用静态方法。更改后的代码将像这样 运行 正确:

    public class tester {
        private static class estupid {
            public static void main(String[] args) {
                System.out.println("Hello Im a static method of a private class and main too");
            }
        }
    
    
    
    public static void main(String[] args) {
        estupid.main(args);
    }
    
    }

编译并运行以上代码后

C:\Himanshu\GitHub\hsingh-learning\src>javac tester.java

C:\Himanshu\GitHub\hsingh-learning\src>java tester
Hello Im a static method of a private class and main too

这只是为了更正您的代码并使其可编译并 运行 可用,但不建议在嵌套 class 中编写 main 方法。 另一件事是,您正在制作私有嵌套 class,因此您无法从控股 class 外部访问它(在您的情况下为测试者 class)。 tester class 是 public 并且 JVM 可以访问,但是嵌套的 class 被标记为私有,因此无法访问。

这并不意味着您不能从 JVM 调用嵌套 class 的主要静态方法。让你的嵌套 class public.

public class tester {
    public static class estupid {
        public static void main(String[] args) {
            System.out.println("Hello Im a static method of a private class and main too");
        }
    }
}

编译它,将生成 2 个 class 文件。 1. tester.class 2. 测试员$estupid.class

运行 第二个 tester$estupid 包含 main 方法(JVM 需要)

C:\Himanshu\GitHub\hsingh-learning\src>java tester$estupid
Hello Im a static method of a private class and main too