线程“main”中的异常 java.lang.RuntimeException:无法编译的源代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14173800/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 15:21:27  来源:igfitidea点击:

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code

java

提问by user1869132

How can I call a non static method in main class.I am getting the folowing error in my sample console application

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

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)

and the code is,

代码是,

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");
    }


}

回答by someone

problem is you have used non static method in static method which is not allowed in java , change doSomthing() as static method

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

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

Or Create an object of Main class and call it

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

 public static void main(String[] args) {
   Main myMain = new Main();
   myMain.doSomthing();
   System.out.print("From Main");
}

回答by Reimeus

You could create an instancefirst from your staticmainmethod:

您可以先从您的方法创建一个实例staticmain

new Main().doSomthing();

回答by Helio Santos

You can't call a non staticmethod in main class, unless you instantiate one [Main class].

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

回答by ZombieSpy

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");
    }
}