1

如何在主类中调用非静态方法。示例控制台应用程序中出现以下错误

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - non-static method doSomthing() cannot be referenced from a static context
        at sample.Main.main(Main.java:20)

代码是,

public class Main  {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
       doSomthing();
       System.out.print("From Main");
    }

    protected void doSomthing()
    {
        System.out.print("From Main doSomthing");
    }


}
4

4 回答 4

5

问题是您在 java 中不允许的静态方法中使用了非静态方法,请将 doSomthing() 更改为静态方法

protected static void doSomthing()
{
    System.out.print("From Main doSomthing");
}

或者创建一个 Main 类的对象并调用它

 public static void main(String[] args) {
   Main myMain = new Main();
   myMain.doSomthing();
   System.out.print("From Main");
}
于 2013-01-05T16:31:04.243 回答
2

您可以先从您的方法创建一个实例:static main

new Main().doSomthing();
于 2013-01-05T16:31:44.930 回答
2

您不能在主类中调用非静态方法,除非您实例化一个 [主类]。

于 2013-01-05T16:33:03.460 回答
2
public class Main  {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
       Main main = new Main();
       main.doSomthing();
       System.out.print("From Main");
    }

    protected void doSomthing()
    {
        System.out.print("From Main doSomthing");
    }
}
于 2013-01-05T16:34:32.340 回答