我怎样在不同类之间进行切换?

huangapple go评论66阅读模式
英文:

How can I change between classes?

问题

这是我写的内容。

public class Test {
    public static void main(String[] args) {
        Object a1 = new A();
        Object a2 = new A();

        System.out.println(a1.toString());

        System.out.println((a1 == a2) + " " + (a1.equals(a2)));
    }
}

class A {
    int x;

    public boolean equals(Object obj) {
        A _obj = (A) obj;
        return x == _obj.x;
    }

    public String toString() {
        return "A's x is " + x;
    }
}
英文:

This is what I wrote.

public class Test {
    public static void main(String[] args) {
        Object a1 = new A();
        Object a2 = new Object();

        System.out.println(a1.toString());
        
        System.out.println((a1 == a2) + " " + (a1.equals(a2)));
    }
}

class A {
    int x;

    public boolean equals(Object obj) {
        A _obj = (A) obj;
        return x == _obj.x;
    }

    public String toString() {
        return "A's x is " + x;
    }
}

How can I make 'false true' on the console? Except revising the main method. Revise only A method.
I tried to make change the Object a2 to an a2. How Can I change that in the A class?

答案1

得分: 3

因为你正在获得错误信息 class java.lang.Object cannot be cast to class A,这是因为你正在将对象与其进行比较的对象不是 A 类的实例,因此试图将对象强制转换为 A 类型将会失败。

在实现 .equals 方法时,你应该始终首先执行以下三个检查,以确保在尝试比较属性之前确保对象的安全性:

  • if (obj == this) return true; 如果两个对象是同一个对象,意味着它们是同一个实例,而不仅仅是具有相同属性的两个对象,立即返回 true,因为无需检查属性。

  • if (obj == null) return false; 这可以防止由于尝试访问 null 对象的属性(例如在你的代码中执行 return x == _obj.x 时)而引发 NullPointerException

  • if (!(obj instanceof A)) return false; 如果对象不是你的类的实例,则类型转换将失败(正如在你的代码中所发生的),这会在尝试强制转换之前返回 false,以防止此类情况发生。

最后,如果代码执行到此处,你可以像在你的代码中所做的那样进行强制转换并比较对象:

A _obj = (A) obj;
return this.x == _obj.x;

请记住,如果你正在比较的属性不是基本类型,你应该对它们使用 .equals 方法。

英文:

The reason you're getting the error class java.lang.Object cannot be cast to class A is because the object you're comparing it to is not an instance of class A, so trying to cast the object as such will fail.

When implementing the .equals method, you should always perform these three checks first to ensure the safety of the object before you try comparing its properties:

if (obj == this) return true; If the two objects are the exact same object, meaning that they are the same instance, not just two objects with the same properties, immediately return true because there is no need to check the properties.

if (obj == null) return false; This prevents a NullPointerException by trying to access a property of a null object (such as when in your code you do return x == _obj.x)

if (!(obj instanceof A)) return false; If the object is not an instance of your class, the typecast will fail (as it did in your code) and this protects against that by returning false before trying to cast.

Finally, if the code reaches this point you can cast and compare the objects as you had done in your code:

A _obj = (A) obj;
return this.x == _obj.x;

Keep in mind that if the properties you are comparing are not primitives, you should use .equals on them

答案2

得分: 0

首先,你所说的“使假变真”是指什么?我猜你想让你的代码运行,但你能否给我们更多关于你尝试做什么的背景信息呢?

你的代码失败的原因是,当你将一个对象实例(a2)传递给equals方法时,你试图将其强制转换为类型为A的引用。但是,由于a2实际上是Object的纯实例,而不是A的实例,所以这个转换失败了。尽管Object是Java中所有东西的基类,包括你自己定义的A,但你的转换方向是错误的。对象没有保持属性x,因此这种转换方式是不安全的。Java的类型检查机制捕捉到这一点,并在尝试转换时抛出错误。

查看一篇关于继承和类型转换的文档,以了解这方面的基础知识。例如,这个链接

英文:

First of all, what do you mean by "making false true" exactly? I assume you want your code to run, but could you give us a bit more context of what you are trying to do?

The reason your code fails is that you are trying to cast your instance of an Object (a2) onto a reference of type A when you pass it into the equals method. But since a2 is actually a pure instance of Object and not of A, this cast fails. Even though Object is the baseclass for everything in Java, including your self defined A, you are casting in the wrong direction. An Object does not hold an attribute x so casting this way would be unsafe. Java's typechecking mechanism catches this and throws an error when you try to cast.

Have a look at a document explaining inheritance and casting to get the basics of this. E.g., this one.

huangapple
  • 本文由 发表于 2020年4月9日 14:09:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/61114956.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定