Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Overriding hashCode and equals methods

Chris JonesApr 18 2011 — edited Apr 18 2011
In the example below, it prints out "true" when the Child objects a and b are different. Should I overide equals and hashCode method for every class which extends Person?

public class EqualsTest {
	public static void main(String[] args){
		
		Child a = new Child("Tom",10,1);
		Child b = new Child("Tom",10,2);
		System.out.println(a.equals(b));
		
		
	}
}

class Person{
	private String name;
	private int height;

	private volatile int hashCode = 0; 

	
	public Person(String n, int h){
		this.name = n;
		this.height = h;
	}
	
	@Override
	public boolean equals(Object obj) {
		if(this == obj){
			System.out.println("hello");
			return true;
		}
		if(obj instanceof Person){
			Person a = (Person)obj;
			if(this.name.equals(a.name)){
				return true;
			}else{
				return false;
			}
		}else{
			return false;
		}
	}
	
	@Override
    public int hashCode () { 
        final int multiplier = 23; 
        if (hashCode == 0) { 
            int code = 133; 
            code = multiplier * code + name.hashCode(); 
            code = multiplier * code + new Integer(height).hashCode(); 
            hashCode = code; 
        } 
        return hashCode; 
    } 

}

class Child extends Person{
	
	private int age;
	
	public Child(String n,int h,  int a) {
		super(n,h);
		this.age = a;
	}
}
Thanks
This post has been answered by baftos on Apr 18 2011
Jump to Answer
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 16 2011
Added on Apr 18 2011
12 comments
806 views