Java 界面与类型铸造
在Java 8关于接口的教程中,表示当类实现接口时,必须将接口类型强制转换为类类型,以便调用此类的方法,如Java 8教程中的以下示例所示:Java 界面与类型铸造,java,Java,在Java 8关于接口的教程中,表示当类实现接口时,必须将接口类型强制转换为类类型,以便调用此类的方法,如Java 8教程中的以下示例所示: public class RectanglePlus implements Relatable { public int width = 0; public int height = 0; public Point origin; // four constructors public Rectangle
public class RectanglePlus
implements Relatable {
public int width = 0;
public int height = 0;
public Point origin;
// four constructors
public RectanglePlus() {
origin = new Point(0, 0);
}
public RectanglePlus(Point p) {
origin = p;
}
public RectanglePlus(int w, int h) {
origin = new Point(0, 0);
width = w;
height = h;
}
public RectanglePlus(Point p, int w, int h) {
origin = p;
width = w;
height = h;
}
// a method for moving the rectangle
public void move(int x, int y) {
origin.x = x;
origin.y = y;
}
// 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;
}
}
简而言之:因为
hashCode
是在中定义的,并且每个其他类都隐式扩展Object
所以当你有
public int compareTo(Card o) {
return this.hashCode() - o.hashCode();
}
编译器已经知道o
属于Card
类型,它扩展了定义hashCode
方法的Object
。不需要显式强制转换
另一方面,在isLargerThan
方法中,参数的类型为Relatable
:
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;
}
public int isLargerThan(相关其他){
矩形加其他矩形
=(矩形加)其他;
if(this.getArea()otherRect.getArea())
返回1;
其他的
返回0;
}
从您提供的链接判断,getArea
方法仅在RectanglePlus
中定义。由于编译器只看到Relatable
,因此此时它对getArea
方法一无所知,您需要显式地将other
强制转换为RectanglePlus
才能访问它
请注意,在强制转换之前,您应该实际执行instanceof
检查,以避免其他
不是矩形加号
时出现类异常
(您不知道是否有其他类实现了相关
)
让我尝试一个与代码无关的示例:
如果人们有宠物,通常会给它起个名字。所以无论你养什么宠物,你都可以问它的名字(参见hashCode)。但是,除非他们知道它是一只狗,否则他们不能让你让它叫(参见getArea
)。
而且您可能无法生成猫吠声(参见
ClassCastException
)。hashCode()是在java.lang.Object中定义的。您可以对任何对象调用该方法。Card
声明了哪些方法?
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;
}