0

该示例来自一门课​​程,用于比较 java 中的两个对象:

public class Complex {

    ...

    public boolean equals (Object obj) {
        if (obj instanceof Complex) {    // if obj is "Complex" (complex number) 
            Complex c =  (Complex) obj   // No idea
            return (real == c.real) && (imag == c.imag); 
            // I'm guessing real means [this].real
        }
        return false;
    }
}

所以,我的问题是:“这是什么意思:Complex c = (Complex) obj实际上是什么意思”?

我也使用过 python 和 c++,java 对我来说是新的。

4

4 回答 4

2

请参阅我的内联评论。

    public class Complex {

...

public boolean equals (Object obj) {
    if (obj instanceof Complex) {    // you first need to check whetever the obhect passed to the equal method is indeed of type "Complex" because i guess what you want here is to compare two Complex objects.
        Complex c =  (Complex) obj   // If the object is complex then you need to treat it as complex so cast it to Complex type in order to compare the "real" and "imag" values of the object.
        return (real == c.real) && (imag == c.imag); 
        // I'm guessing real means [this].real
        // yes, it does.
    }
    return false;
}

}

type casting此处阅读更多信息

您还可以检查boxing and unboxing概念。

希望这会有所帮助,丹

于 2012-10-20T10:57:49.420 回答
2
obj instanceof Complex  

这意味着 obj 可能是 Complex 或其子类的实例。

Complex c =  (Complex) obj  

意味着如果它是子类对象,则将其类型转换为复杂类对象

于 2012-10-20T10:51:36.213 回答
1

这意味着将输入Object类型转换为Complex类型,在此行之后您可以使用Complex类中的所有 api。

于 2012-10-20T10:51:58.120 回答
0
  Complex c =  (Complex) obj  

Typecasting Complex 是将对象 obj 类型转换为 Complex 类型的类

可以参考此链接以获取 C++ 对 Java 的参考

如果错了请纠正我

于 2012-10-20T11:00:09.847 回答