Java 主方法不调用静态方法

Java 主方法不调用静态方法,java,methods,static,Java,Methods,Static,我读过静态方法不能调用非静态方法,但是这个编译,主(静态)方法调用maybeNew(非静态)方法,你能给我一个线索吗 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) {

我读过静态方法不能调用非静态方法,但是这个编译,主(静态)方法调用maybeNew(非静态)方法,你能给我一个线索吗

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

}
公共类Mix4{
int计数器=0;
公共静态void main(字符串[]args){
整数计数=0;
Mix4[]m4a=新的Mix4[20];
int x=0;

虽然(x您不能直接从静态方法调用非静态方法,但始终可以使用类的对象从静态方法调用非静态方法

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

“但是这个编译”-因为您创建了一个
Mix4
的实例,在该实例上您调用了该方法。如果您试图按原样调用
maybeNew(1);
(即,没有任何其他前缀),你会的。你已经创建了一个Mix4实例,它是一个局部变量。这是在静态方法中访问非静态的传统方法。有关更多信息,请参阅这些。谢谢Turing85。谢谢Asel Siriwardena。你在哪里读到的?(这必须是可能的,否则将永远不会运行/调用非静态方法,因为所有程序都从static
main
启动)顺便说一句
println()
也是非静态的