Search code examples
javamethodsstaticprogram-entry-point

Why should my method be static?


Hi I have this piece of code and i am really confused to why i have to make the lel method static.The error is this "non static method cant be referred from static content". Usually when I create methods either to construct new objects or to manipulate objects in the main method I do not get this error message.Plus, i never declared e to be static!!. can someone please explain to me why this occurring?? Thank you :)

class x {

    public static void main(String[]args){

        int e= 2232;

        e= lel(e);

    }

    int lel(int k){
        return k+1;
    }
}

Solution

  • There are two solutions you could implement. The first option is to make your int lel(int k) a static method which would look like static int lel(int k)

    Your other option is to declare a new object of your class x and use that for your lel method within main as MickMnemonic suggested in the comments. That code would look like:

    e = new x().lel(e);

    I believe the simplest thing would be to make the lel method static but it is up to you.

    A deeper explanation of static methods can be found here.