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;
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With