当前位置: 代码迷 >> J2SE >> 关于Java小程序的一个异常
  详细解决方案

关于Java小程序的一个异常

热度:27   发布时间:2016-04-23 20:04:13.0
关于Java小程序的一个错误
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);
    } 
}