PDA

View Full Version : What is Instance, Empty Constructor .... in Java


tking88
Oct23-09, 09:46 AM
How come will return false I put in 2 same name it should return true ?

Teacher p1= new Teacher("Nelson");
System.out.println(p1);
Teacher p2= new Teacher("Nelson");
System.out.println(p2);

System.out.println(p1.equals(p2));

it print out false


I do testing on below it give me ture how come the above not give me true

p1 = "Nelson";
p2 = "Nelson";
System.out.println(p1.equals(p2));

silverfrost
Oct24-09, 07:01 AM
Without knowing much about Java (i.e. I could be wrong):

The equals method probably has a default implementation that just compares the two pointers and returns true or false depending on it.

so:


Teacher p1= new Teacher("Nelson");
System.out.println(p1);
Teacher p2= new Teacher("Nelson");
System.out.println(p2);


p1.equals(p2)

actually calls (say)


bool object.equals(object p2)
{
return p2==this;
}


Whereas... in your second example you had strings and string will have a specific equals method that compares strings as you expect.

So... write an equals that overrides the default one.

tking88
Oct24-09, 10:36 AM
K I did something like this and all ok now it return the true compare value


public boolean equals(Object o)
{
System.out.println(o instanceof Moof);
System.out.println(((Moof)o).getMoofValue());
System.out.println(this.moofValue); //XXX
if ((o instanceof Moof) && (((Moof)o).getMoofValue() == this.moofValue))
{
return true;
}
else
{
return false;
}