JAVA - 无法对非静态方法进行静态引用

标签 java methods static

<分区>

public class lookFor {

    //Tools
    //It returns the position of an element at the ArrayList, if not found returns -1
    public int User(String target, ArrayList<User> users){
        for(int i = 0; i < users.size(); i++){
            if(users.get(i).getUserName().equals(target)){
                return i;
            }
        }
        return -1;
    }
}

出于某种原因,当我尝试调用“用户”时 This Error appears

并要求我将“user”方法设为静态方法,但我不知道它会产生什么影响。

最佳答案

静态方法属于类,非静态方法属于类的实例。
您需要创建该类的一个实例:

 lookFor look = new lookFor();

然后这样写:

 if(look.User(username,users)==-1){....};

Static means there is one for an entire class, whereas if it is non-static there is one for each instance of a class (object). In order to reference a non-static method you need to first create an object, and call it.

关于JAVA - 无法对非静态方法进行静态引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33970140/

相关文章:

java - 使用 BigInteger 参数调用方法时出现问题

c++ - C++中静态函数的区别

swift - Swift 中 "static var"和 "var"的区别

java - 旋转轮作为android中的菜单,菜单项每天都在变化

java - 如何从 html 对象标签内部编码/解码查询字符串?

java - 保持 HttpServer 的 Activity

java - Android 使用一种方法处理多个 View

python - 覆盖父类的方法

Python:尝试将函数参数传递给类中的另一个函数,得到 NameError:未定义名称 ' '

java - 如何初始化最终对象数组