因此,我在网上查阅了大量资源,以了解Java接口。我相信我对它们有很好的总体理解,但在编程时我有点困惑……
我创建了一个名为A的接口,里面有以下内容...
public interface A {
public int sum(int first, int second);
}然后我创建了一个名为B的类。
public class B implements A {
public static void main(String [] args){
int result = sum(3, 5);
}
public int sum(int first, int second) {
int total = first + second;
return total;
}
}现在我想弄清楚的是如何正确地调用/使用"sum“方法。在Eclipse中,我得到了"int result = sum(3,5);“这一行的错误,它告诉我将该方法设为静态方法。如果我把它设为静态的,那么方法需要在接口中匹配它。但是,我不能在接口中使用静态方法?
感谢您的帮助,感谢您抽出时间阅读我的问题。
发布于 2013-01-30 07:49:20
您遇到的问题不是接口的问题,而是static方法的问题。
main是一种static方法。这意味着它不是链接到对象/实例,而是链接到类本身。
由于您想要使用sum,这是一个实例方法,您首先需要创建一个对象来调用它的方法。
A a = new B();
int result = a.sum(5, 6);通常,实例方法更多地与对象状态相关联,而静态方法更像非面向对象语言中的“过程”。在使用sum的情况下,您的方法作为静态方法会更有意义。但是,如果您使用B包装一个值(状态),并使用sum将其添加到您的内部状态,那么这将结束(以一种更面向对象的方式)。
A a = new B(5);
a.sum(6);
int result = a.getValue();请注意,这两种方法都是有效的,并且都是用Java编译的,只需选择在每种情况下更有意义的修饰符即可。
发布于 2013-01-30 07:49:14
不能从main方法调用sum(),因为sum是一个实例方法,而不是静态方法。它需要从类的实例中调用。
你需要实例化你的类:
public static void main(String [] args) {
B b = new B();
int result = b.sum(3, 5);
}发布于 2013-01-30 07:49:20
public class B implements A {
public static void main(String [] args){
int result = new B.sum(3, 5);
// Create an instance of B so you can access
// the non-static method from a static reference
// Or if you want to see the power of the interface...
A a = new B();
int result = a.sum(3, 5);
}
public int sum(int first, int second) {
int total = first + second;
return total;
}
}https://stackoverflow.com/questions/14594221
复制相似问题