我已经读过静态方法不能调用非静态方法,但是这个编译方法,main(static)方法调用了MayNew(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");
}
}