Java 什么是车辆其他=(车辆)obj;做

Java 什么是车辆其他=(车辆)obj;做,java,Java,我对什么Vehicle other=(Vehicle)obj感到困惑可以。它是否创建变量other并将obj复制到其中 @Override public boolean equals (Object obj) { if (this == obj) return true; if (!(obj instanceof Vehicle)) return false; Vehicle other = (Vehicle)obj; return ( type.equals

我对什么
Vehicle other=(Vehicle)obj感到困惑可以。它是否创建变量
other
并将
obj
复制到其中

@Override
public boolean equals (Object obj) {
    if (this == obj) return true;
    if (!(obj instanceof Vehicle)) return false; 

    Vehicle other = (Vehicle)obj;
    return ( type.equals(other.type) 
            && size == other.size
            && uitstoot == other.uitstoot
           );
}

首先检查
obj
是否为
Vehicle

if(!(车辆obj实例))返回false

如果是,则将其转换为
车辆
类别-即从该点开始,它将被解释为
车辆
实例

Vehicle other = (Vehicle)obj;

它有两个功能。它将
other
声明为
Vehicle
引用,并将其初始化为指向
obj
引用的对象的指针。强制转换不会导致运行时异常,因为该对象已被确定为
车辆

我认为您是正确的

首先,它将对象obj转换为Vehicle类(我们已经检查过obj可以转换为Vehicle类,否则代码无法转到此处)


其次,将副本提供给其他变量,以保护原始数据

它不是那样做的。它提供了一个参考。这很有意义!谢谢此equals方法在Vehicle类中实现,这是否意味着您需要在每个类中重写equals方法,如果您想在该类中使用equals?对象类中的equals()只执行instanceof检查。见:是的。您必须在每个类中重写
equals
hashcode
,以便能够在
集合中进行相等比较或使用。更多信息: