What is Instance, Empty Constructor in Java

  • Context: Comp Sci 
  • Thread starter Thread starter tking88
  • Start date Start date
  • Tags Tags
    Empty Java
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
2 replies · 4K views
tking88
Messages
2
Reaction score
0
What is Instance, Empty Constructor ... in Java

How come will return false I put in 2 same name it should return true ?

Code:
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
Code:
false


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

Code:
p1 = "Nelson";
p2 = "Nelson";
System.out.println(p1.equals(p2));
 
Last edited:
Physics news on Phys.org


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:

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

p1.equals(p2)

actually calls (say)

Code:
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.
 


K I did something like this and all ok now it return the true compare value

Code:
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;
}