如何从主方法调用非静态方法? [英] How do I call a non static method from a main method?

查看:134
本文介绍了如何从主方法调用非静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

For example, I am trying to do something like this

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]);

    }
}

我收到一条错误消息,告诉我我无法从静态环境中引用非静态变量.因此,如果这是真的,我将如何在 main 中使用非静态方法?

I get an error telling me that I can't reference non-static variables from static enviorments. So if that is true how would I ever utilize a non static method inside of a main?

推荐答案

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

You can't. A non-static method is one that must be called on an instance of your Test class; create an instance of Test to play with in your main method:

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]);

    }
}

这篇关于如何从主方法调用非静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆