Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-static method cannot be referenced from static content

Tags:

java

I cannot compile the following code:

public class Test {
 public static void main (String [] args ){
  int a = calcArea(7, 12);
  System.out.println(a);
 }

 int calcArea(int height, int width) {
  return height * width;
 }
}

The following error appears:

Non-static method calcArea(int, int) cannot be referenced from static content

What does it mean? How can I resolve that issue..?

EDIT:

Based from your advice, I made an instance which is new test() as follows:

public class Test {
    int num;
    public static void main (String [] args ){
        Test a = new Test();
        a.num = a.calcArea(7, 12);
        System.out.println(a.num);
    }

    int calcArea(int height, int width) {
            return height * width;
    }

}

Is this correct? What is the difference if I do this...

public class Test {
 public static void main (String [] args ){
  int a = calcArea(7, 12);
  System.out.println(a);
 }

 static int calcArea(int height, int width) {
  return height * width;
 }
}
like image 276
newbie Avatar asked Dec 02 '22 03:12

newbie


1 Answers

Your main is a static, so you can call it without an instance of class test (new test()). But it calls calcArea which is NOT a static: it needs an instance of the class

You could rewrite it like this I guess:

public class Test {
 public static void main (String [] args ){
  int a = calcArea(7, 12);
  System.out.println(a);
 }

 static int calcArea(int height, int width) {
  return height * width;
 }
}

As comments suggests, and other answers also show, you might not want to go this route for evertyhing: you will get only static functions. Figure out what the static actually should be in your code, and maybe make yourself an object and call the function from there :D

like image 122
Nanne Avatar answered Dec 05 '22 00:12

Nanne