我读到静态方法不能调用非静态方法,但是这次编译,main(static)方法调用了maybeNew(no-static)方法,你能给我一个线索吗?
public class Mix4 {
int counter = 0;
public static void main(String[] args) {
int count = 0;
Mix4[] m4a = new Mix4[20];
int x = 0;
while (x<9) {
m4a[x] = new Mix4();
m4a[x].counter = m4a[x].counter + 1;
count = count + 1;
count = count + m4a[x].maybeNew(x);
x = x + 1;
}
System.out.println(count + " " + m4a[1].counter);
}
public int maybeNew(int index) {
if (index<5) {
Mix4 m4 = new Mix4();
m4.counter = m4.counter + 1;
return 1;
}
return 0;
}
}
最佳答案
您不能直接从静态方法调用非静态方法,但始终可以使用类的对象从静态方法调用非静态方法。
public class Main {
public static void main(String[] args) {
// sayHello(); // Compilation error as you are calling the non-static method directly from a static method
Main main = new Main();
main.sayHello();// OK as you are calling the non-static method from a static method using the object of the class
}
void sayHello() {
System.out.println("Hello");
}
}
关于java - main 方法调用非静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59900823/