简体   繁体   中英

Trouble with understanding equals method in Java

I'm learning Java from mooc course and I have problem with understanding this example of writing method that will be comparing objects:

public class Person {

private String name;
private int age;
private int weight;
private int height;

// constructors and methods


public boolean equals(Object compared) {
    // if the variables are located in the same position, they are equal
    if (this == compared) {
        return true;
    }

    // if the compared object is not of type Person, the objects are not equal
    if (!(compared instanceof Person)) {
        return false;
    }

    // convert the object into a Person object
    Person comparedPerson = (Person) compared;

    // if the values of the object variables are equal, the objects are equal
    if (this.name.equals(comparedPerson.name) &&
        this.age == comparedPerson.age &&
        this.weight == comparedPerson.weight &&
        this.height == comparedPerson.height) {
        return true;
    }

    // otherwise the objects are not equal
    return false;
}

// .. methods
}

Despite it being commented upon each step, I don't understand the fact that the method keeps going after

 if (!(compared instanceof Person)) {
        return false;
    } 

So, if "compared" isn't Person type object it returns false, so the method should just stop working, but then there are instructions that enable making it the same type of object that we're comparing it with. Can somebody explain to me, how is it possible that after returning false, the object with "wrong" type can be converted and compared despite not satysfying condition above, which should result in ending the method?

If Compared is not a Person the method returns false (ie not equal) and finishes.
But if you call equals with an object of type Person the condition is not met and the method does not return false but continues. And if that happens we know compared must be of type Person . But the compiler doesn't know that (it could if it was smarter, but it isn't). So the line

Person comparedPerson = (Person) compared;

does not 'convert' anything. The comment is misleading. This typecast just tells the compiler our object is in fact of type Person . And this allows the following code to use it as a Person and call Person methods.

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