在下面的代码中,假设方法equals
属于类Rectangle
,我想知道为什么需要对参数object
进行强制转换> 当 if
条件已确定 object
是矩形时,作为矩形。
public boolean equals(Object object)
{
boolean equal;
if (object != null && this.getClass() ==
object.getClass())
{
Rectangle other = (Rectangle) object;
equal = (this.width == other.width) &&
(this.height == other.height);
}
else
{
equal = false;
}
return equal;
}
最佳答案
编译器不知道这个对象
有一个名为width
的字段。但是other
是一个矩形
- 因此编译器知道会有一个宽度
和一个高度分别为
字段。
我建议您不要进行强制转换,直接使用对象并查看收到的错误。
关于java - 为什么要转换一个已经被标识为特定类的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37303425/