如何从main方法调用非静态方法?

tob*_*ats 6 java static non-static

例如,我正在尝试做这样的事情

public class Test {

    public static void main(String args[]) {

        int[] arr = new int[5];

        arrPrint(arr);
    }

    public void arrPrint(int[] arr) {

        for (int i = 0; i < arr.length; i++)
            System.out.println(arr[i]);

    }
}
Run Code Online (Sandbox Code Playgroud)

我收到一个错误,告诉我无法从静态环境中引用非静态变量.所以,如果这是真的,我怎么能在主要内部使用非静态方法?

fr1*_*50n 14

你不能.非静态方法是必须在Test类的实例上调用的方法; 在main方法中创建一个Test实例:

public class Test {

    public static void main(String args[]) {
        int[] arr = new int[5];
        arr = new int[] { 1, 2, 3, 4, 5 };

        Test test = new Test();
        test.arrPrint(arr);

    }

    public void arrPrint(int[] arr) {
        for (int i = 0; i < arr.length; i++)
            System.out.println(arr[i]);

    }
}
Run Code Online (Sandbox Code Playgroud)