public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
System.out.println(sum(a, b));
}
int sum(int a, int b) {
return (a + b);
}
}代码如上,在System.out.println那行有错误,错误信息如下:
Cannot make a static reference to the non-static method sum(int, int) from the type Test,里面提示只要把sum方法改成static即可,究竟是怎样一回事呢?
------解决思路----------------------
没有构建对象,不可以调用非静态方法。
可以改为:
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
System.out.println(sum(a, b));
}
public static int sum(int a, int b) {
return (a + b);
}
}或:
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
Test t = new Test();
System.out.println(t.sum(a, b));
}
int sum(int a, int b) {
return (a + b);
}
}