“线程中的异常”;“主要”;java.lang.RuntimeException:不可编译的源代码
如何在main类中调用非静态方法。我在示例控制台应用程序中遇到以下错误“线程中的异常”;“主要”;java.lang.RuntimeException:不可编译的源代码,java,Java,如何在main类中调用非静态方法。我在示例控制台应用程序中遇到以下错误 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 clas
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");
}
}
问题是您在静态方法中使用了非静态方法,这在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");
}
问题是您在静态方法中使用了非静态方法,这在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");
}
您可以首先从static
main
方法创建实例:
new Main().doSomthing();
您可以首先从static
main
方法创建实例:
new Main().doSomthing();
除非实例化一个[main class],否则不能在main class中调用非静态方法。除非实例化一个[main class],否则不能在main class中调用非静态方法.为什么要从静态方法调用非静态方法?为什么要从静态方法调用非静态方法?或者您可以按照staticauthor的要求“调用非静态方法”更改方法,或者您可以按照staticauthor的要求“调用非静态方法”更改方法。谢谢。因此,在控制台应用程序中,所有方法都应该是静态的。是吗?您可以创建该类的对象并调用您的方法,但并不总是静态的。谢谢。因此,在控制台应用程序中,所有方法都应该是静态的。是吗?您可以创建该类的对象并调用您的方法,但并不总是静态的。
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");
}
}