Comp Sci What is Instance, Empty Constructor in Java

  • Thread starter Thread starter tking88
  • Start date Start date
  • Tags Tags
    Empty Java
AI Thread Summary
In Java, the default implementation of the equals method compares object references, which is why two instances of the Teacher class with the same name return false when compared. In contrast, the String class has a specific equals method that compares the actual string values, resulting in true for two identical strings. To achieve similar behavior for custom classes, such as Teacher, it is necessary to override the equals method to compare the relevant attributes. The provided example demonstrates how to implement this by checking if the object is an instance of the class and comparing specific values. Properly overriding the equals method ensures accurate comparisons between object instances.
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;
}
 

Similar threads

Replies
12
Views
2K
Replies
7
Views
3K
Replies
2
Views
1K
Replies
1
Views
2K
Replies
6
Views
2K
Replies
2
Views
4K
Back
Top