首页 新闻 赞助 找找看

关于Cannot make a static reference to the non-static method sum(int, int)

0
悬赏园豆:30 [已关闭问题] 关闭于 2014-12-30 16:05
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即可,究竟是怎样一回事呢?先谢园友了。

bobo2018的主页 bobo2018 | 初学一级 | 园豆:135
提问于:2014-12-28 13:49
< >
分享
所有回答(2)
0

main是static,调用的sum也必须是。

爱编程的大叔 | 园豆:30839 (高人七级) | 2014-12-28 14:34

从错误信息来看,的确是这样,但是我写了以下代码来测试下到底是不是这样,

1 public class Test {
2 
3     public static void main(String[] args) {
4         
5         String string = "abc";
6         
7         System.out.println(string.indexOf("a"));
8     }
9 }

代码里面,main方法同样调用了不是static的方法indexOf(),但是这段代码没有报错,如原问题,请问这到底是怎么一回事呢?先谢了。

支持(0) 反对(0) bobo2018 | 园豆:135 (初学一级) | 2014-12-29 12:33

@VVL1295: indexof明显就是static的方法。

indexOf是扩展方法, 你注意一下string类是sealed。

反正你记住,staick方法只能调用static的方法或是变量。

支持(0) 反对(0) 爱编程的大叔 | 园豆:30839 (高人七级) | 2014-12-29 13:25

@爱编程的大叔: 你好,String类的确是不能被继承的,你所说的“扩展方法”是指什么方法?我的那个小程序,反映出来的却是static的main方法可以调用非static的方法,API帮助文档里面是这样写的:public int indexOf(String str),也就是说indexOf()不是static方法,请问是怎么回事?

支持(0) 反对(0) bobo2018 | 园豆:135 (初学一级) | 2014-12-29 17:00

@VVL1295: 你的好奇心太重了,这么好奇的话,你应该多GOOGLE,而不是问。

打破砂锅问到底对于研究是好,但有时候你应该明白什么是约定。

C# v1 did not allow 'static' keyword on class. So if you have a class with only static methods, it was suggested to declare it 'sealed', 'abstract' and make constructor private. This means that no one can instantiate your class or try to inherit from it. [It doesn't make sense to inherit from a class which has only static methods.]

C# v2 allowed the static keyword on a class so you don't have to use the above trick to enforce correct usage.

 

首先,indexOf这个方法定义是在string这个Class里面的,而string这个Class整个就是sealed的,这时候已经没有必要在方法上再写static,在这里面所有的方法都一定是static的。string类是无法new的,所以里面的方法一定是static的。

 

看了半天,才注意到你是JAVA,不过差不多也是这个道理了。

支持(0) 反对(0) 爱编程的大叔 | 园豆:30839 (高人七级) | 2014-12-29 17:14

@爱编程的大叔: 对呀,看到sealed就觉得不对劲了,总然而之,谢了哈。

支持(0) 反对(0) bobo2018 | 园豆:135 (初学一级) | 2014-12-29 19:39
0

一个很低级的错误,应该创建Test类的对象,然后使用对象.sum()的方式调用sum()方法,或者把sum()改成static的(至于为什么不用Test.sum(),我猜想可能因为static方法是随着类加载而加载的,这里Test类已经加载了,所以不必带上类名,直接使用sum()即可)。

bobo2018 | 园豆:135 (初学一级) | 2014-12-30 00:46
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册