简体   繁体   中英

Java objects instanceof

The instructions say: Create an equals method that takes an object reference and returns true if the given object equals this object. * Hint: You'll need 'instanceof' and cast to a (Position)

I have:

class Position {

    private double x,y;
    private int id;

public boolean instanceOf(Object a)
    {
        boolean isInstance;
        if ((Position)a instanceof Position)
            isInstance=true;
        else
            isInstance=false;
        return isInstance;
    }

But I'm doing it wrong, and I dont know what my problem is. I'm new to objects so this is kind of confusing me..

He clearly said create an equals() method, and you got it right here as well. But even after all this you created a method named instanceOf() . Why?

Moreover, you may get a ClassCastException on this line, in case some other type of object is passed.

    if ((Position)a instanceof Position)

Which means, precisely, that you should only cast the object to Position , after making sure that the object passed is of type Position . Which means now its good to go further with comparison. If its not of type Position in the first place, then why should you bother comparing it further. Because it can never be equal. I hope you are getting my point.

[Edited to answer the question in comment]

Well, the actual instance should be of type Position. Once we know that its of type Position using instanceof operator, we know its safe to cast it to type Position from type Object. Now the question is why we need to cast? Because initially the instance was of type Object, and we were not sure about the actual type. You might already know that in Java you can assign any type to Object type, because Object is a parent of every class in Java. Hence, before applying instanceof we were not sure about the type of instance.

In case, you don't cast it, you will never be able to access its properties, namely, x, y, and id. You can try accessing any of these on actual object without casting. You will know you can't. Hence, you can't compare those either. I hope, this made it clear.

As this is a homework question, I won't give a detail answer. You have to implement a equals() method, not a instanceOf() method. I think this link help:

The code example in them should be sufficient. Ask again if you need more hint.

Even though the Object a is of a Position type, but it is defined as Object type. In order to access the properties of Position a , we have to cast Object a to Position p using

Position p = (Position)a; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM