简体   繁体   中英

Regarding Equals in java with Objects and Classes

Lets say in java I have a Class A and a Class B which extends A.

Note: classes A and B don't have an equals method in them!

I do:

A a = new B();
B b = new B();
a.equals(b);

It comes out false. I thought when we did equals it dynamically bounded to a and b which would make it true. Or is it because at compile time it looks at a and assumes equals would be equals(A) and since its a B for B b = new B(); it says false? Or am i wrong on both fronts?

As you are not overriding equals then it will use Object 's method

If you have a look at the source code for Object

 @param   obj   the reference object with which to compare.
 public boolean equals(Object obj) {
    return (this == obj);
 }

Obviously a has a different refernce to b thus false

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