Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA - Cannot make a static reference to the non-static method [duplicate]

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

For some reason, when i try to call "User" This Error appears

And asks me to make the "user" method a static method, but i don't know what repercussion will it have.

like image 897
nais Avatar asked Jul 25 '26 14:07

nais


2 Answers

A static method belongs to the class, a non-static method belongs to an instance of the class.
You need to create an instance of the class:

 lookFor look = new lookFor();

And write like this:

 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.

like image 137
Abdelhak Avatar answered Jul 27 '26 03:07

Abdelhak


In order to use the User method in a static context (main method for the example), you need to instantiate the lookFor class and call the User method on that object :

lookFor look = new lookFor(); // Use appropriate constructor
if(look.User(username, users) == -1) {
    ...
}
like image 29
Mohammed Aouf Zouag Avatar answered Jul 27 '26 04:07

Mohammed Aouf Zouag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!