简体   繁体   中英

Overriding equals() method in Java (OCJP)

I am working on OCJP dumps and there is one question:

public class Person{
    private String name;
    public Person (String name) {this.name=name;}
    public boolean equals(Person p){
       return p.name.equals(this.name);
    }
}

Which statement given the above code is true?

A. the equals method does not properly override the Object.equals method

B. compilation fails because the private attribute p.name cannot be accessed in line 5

C. To work correctly with hash-based data structures, this class must also be implement the hashCode method.

D. When adding Person objects to a java.util.Set collection, the equals method in line 4 will prevent duplicates.

In the dump the right answer is A. I think the equals method won't work because p.name is private. Thus B is also right. If B is not right, what is the other problem with the equals method?

A. the equals method does not properly override the Object.equals method.

A is the correct answer. Because the signature of the equals method is:

public boolean equals(Object obj)

I think the equals method won't work because p.name is private. Thus B is also right

name is a private member, but private member are always accessible within the declared class. You are overriding the equals in the same class. So it will compile. So B is not a correct answer.

A. is true because the equals method in class Object has the signature

public boolean equals(Object other);

and therefore can not be overridden by a method

public boolean equals(Person other);

because the parameter type does not match.

B. is false, because a private modifier restricts access to the body of the top level class it is declared in (not the current object, as you seem to think) and declaration and access occur within the body of the same class, and the access is therefore entirely valid.

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