Static reference giving error while accessing

Asked

Viewed 94 times

3

My code is giving a static reference error, what that information means?

  public class inicio {
       public static void main(String[] args) {

               System.out.println(soma(2,2));

       }
       public int soma(int n,int m){
             int num = n+m;
             return num;
       } 
 }
  • which error message?

  • Hello Lodi. Is giving -cannot make a reference Static to the type .

1 answer

5


You created an instance method called soma(). It is instance because this is the standard of class methods in Java. So to use it has to be through a created object, you can’t just call the method directly.

The method main() is static, so unlike the other method it belongs to the class and not to the object. There is only one for the application. When you call soma() in it without being attached to an object it is expected that it is also static, and this is what is missing in the other method to work:

public static int soma(int n, int m) {
    return n + m;
}

I put in the Github for future reference.

It is possible instead to create such an instance and then call the method by this object, but this does not make sense in this case, without state an object should not be created.

I would study object orientation before proceeding. It does not go on the kick that does not learn. In fact before I learned OOP I would learn almost all the other things about programming, they are more important than that. For now know that the basics when using a method it must be static to behave as a function and not a method.

  • @Cool, Thank you.

  • @Carlosheuberger yes, it works, but it doesn’t make sense to do it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.