【问题标题】:How to get attributes from an Object type in Java如何从 Java 中的 Object 类型中获取属性
【发布时间】:2022-01-12 18:41:49
【问题描述】:

我正在尝试为我的 Java 类实现 public boolean equals(Object other) 方法,其中第一个参数作为 Object 类型传递。问题是我不知道如何访问 Object 类型的属性。

【问题讨论】:

标签: java eclipse class oop


【解决方案1】:

Object 是一个非常通用的类,单独使用可能对您没有什么用处。

如果您尝试访问其他类的属性,则需要检查 Object otherYourClass 的实例,然后对其进行转换。

[在此处输入链接描述][1]

class yourClass {
    @Override
    public boolean equals(Object other) {
        // nothing to compare if other is null
        if(other == null) return false;

        // Can only be equals if they are both YourClass
        if(other instanceof YourClass){
            // Tell java to make other into YourClass instead of Object
            YourClass yourClass = (YourClass)other

            //Access properties of another here
            //...
        }

        // other is not an instance of YourClass so it cant be equals
        return false;
}


  [1]: https://stackoverflow.com/questions/8180430/how-to-override-equals-method-in-java

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-29
    • 1970-01-01
    • 2021-12-04
    • 2010-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多