основной метод, вызывающий метод no-stati c - PullRequest
1 голос
/ 24 января 2020

Я прочитал, что метод stati c не может вызвать метод no-stati c, но этот компилятор, основной (stati c) метод, вызывает метод MaybeNew (no-stati c) Можете ли вы дать мне подсказку?

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

}

1 Ответ

2 голосов
/ 24 января 2020

Вы не можете вызвать метод non-stati c напрямую из метода stati c, но вы всегда можете вызвать метод non-stati c из метода stati c, используя объект класса.

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");
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...