java - main 方法调用非静态方法

标签 java methods static

我读到静态方法不能调用非静态方法,但是这次编译,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/

相关文章:

java - Glassfish 4 中 ManagedExecutorService 的设置被忽略

java - Mysql连接器j错误

c# - 如何在文本框为空时输入默认值

java - 复制链表节点并将其插入到链表中间

c++ - Windows Vista 上 Qt 中的静态构建

java - Java程序中的正则表达式查询

java - getOrCreate 函数是好的还是坏的做法?

java - 这种显示图像的方法有什么问题?

c - 如何为每个函数调用检索静态变量

java - println 的非静态替换