如何在主类中调用非静态方法。我在示例控制台应用程序中收到以下错误
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");
}
}
答案 0 :(得分: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");
}
答案 1 :(得分:2)
您可以先使用static
main
方法创建实例:
new Main().doSomthing();
答案 2 :(得分:2)
除非您实例化一个[Main class],否则不能在主类中调用非静态方法。
答案 3 :(得分: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");
}
}