我一直在阅读有关java中的接口(interface)的内容。总的来说,除了一个问题之外,我理解了这个概念。在 http://goo.gl/l5r69 (docs.oracle),在注释中写道,我们可以对接口(interface)和实现它的类进行类型转换。那就是
public interface Relatable {
public int isLargerThan (Relatable other) ;
}
public class RectanglePlus implements Relatable {
public int width = 0;
public int height = 0;
public Point origin;
// four constructors
// ...
// a method for computing the area of the rectangle
public int getArea() {
return width * height;
}
// a method required to implement the Relatable interface
public int isLargerThan(Relatable other) {
RectanglePlus otherRect = (RectanglePlus) other;
if (this.getArea() < otherRect.getArea()) {
return -1;
} else if (this.getArea () > otherRect.getArea()) {
return 1;
} else {
return 0;
}
}
}
如何将 otherRect(这是一个接口(interface))转换为 RectanglePlus。令人困惑的是, RectanglePlus 是一个具有变量的类,这些变量不存在于另一个接口(interface)
中最佳答案
我不得不承认,您展示的 java 文档中的示例非常糟糕且令人困惑。 这很糟糕,因为它包含向下层次结构进行不安全的强制转换。 向上强制转换(从实现类到接口(interface)/父类(super class))始终是安全的,但应尽可能避免向下强制转换。
理想情况下,Relatable
接口(interface)还应包含 getArea()
方法:
public interface Relatable {
public int isLargerThan(Relatable other);
public int getArea();
}
现在您不需要丑陋的 Actor 阵容,只需:
public int isLargerThan(Relatable other) {
if (this.getArea() < other.getArea()) {
return -1;
} else if (this.getArea () > other.getArea()) {
return 1;
} else {
return 0;
}
}
就够了。我还认为 isLargerThan(Relatable other)
是一个坏名字(更大是指什么?)。它可能应该类似于 hasBiggerArea(Relatable other)
,以便它解释我们实际比较的内容(只有“更大”才相当流行)。
关于Java:接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24802425/