java - 学校的一个小例子遇到了麻烦

标签 java

该示例来自类(class),用于比较 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 对我来说是新的。

最佳答案

查看我的内联评论。

    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

您还可以检查装箱和拆箱概念。

希望这有帮助, 丹

关于java - 学校的一个小例子遇到了麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12987640/

相关文章:

java - Android 抽屉导航 onItemSelect 不起作用

Java 防止返回 null

java - JVM 如何收集 ThreadDump 底层

java - 从 JavaFX 程序为 WebView 执行 Javascript 函数

java - 我应该如何以与放置它们的方式相反的顺序存储我希望访问的对象

java - 动态规划 - 获取网格中从起点到终点的路径数

java - 无法从Spark SQL插入到Hive分区表

java - 使用标准 OBJECT 标签,如何显示带有自动提示安装 Java 和后备内容的 Java 小程序?

java - Java继承中的私有(private)方法

Java 8 流的最大值(Math::max)