来自学校的一个小例子有困难

时间:2012-10-20 10:47:17

标签: java

示例来自一个课程,它用于比较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 个答案:

答案 0 :(得分:2)

obj instanceof Complex  

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

Complex c =  (Complex) obj  

意味着如果它是子类对象

,则将它类型转换为Complex类对象

答案 1 :(得分: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;
}

}

here

了解type casting的详情

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

希望这有帮助, 丹

答案 2 :(得分:1)

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

答案 3 :(得分:0)

  Complex c =  (Complex) obj  

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

的类

可以参考reference for C++ reference to Java

的此链接

如果错了,请纠正我