调用非静态方法的主要方法

问题描述 投票:-1回答:1

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

}
java methods static
1个回答
1
投票

您不能直接从静态方法中调用非静态方法,但是始终可以使用类的对象从静态方法中调用非静态方法。

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");
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.