The Java compareto() method returns ClassCastException

Suppose I have an employee base class and a manager subclass, which extends employee Now suppose I create an object x of type employee and an object y of type manager, and call x.compareto (y) to trigger no exception and compare X and y, because the employee, that is, y, is forced to be an employee, but when I call y.compareto (x), I get a ClassCastException I need to know why this happens and how to prevent X. CompareTo (y) from executing, because X and Y come from different classes My idea is to use the getClass () method in the reflection class, as shown below:

if (getClass() != other.getClass()) 
throw new ClassCastException();

I also want to know if there are other ways to achieve this

Solution

You should implement CompareTo () in the Employee class and start it with the following command:

Employee o = (Employee)other;

Then continue to compare it with O – this will ensure that you compare the two employees (this is the lowest common standard)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>