Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

equals()

 
Sai Ram9
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class MyClass
{
static int maxelements;
MyClass(int maxelements)
{
this.maxelements = maxelements;
}
}
public class Q19
{
public static void main(String[] args)
{
MyClass a = new MyClass(100);
MyClass b= new MyClass(100);
if(a.equals(b))
System.out.println("objects have the same value");
else
System.out.println("objects have different values");
}
}
answer says: objects have different values.
Please somebody explain me....
 
qionghua yang
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
When a.equals(b) is called, it will call the super class Object's equals method. This equals methos will check to see if the two object references are point to the same object. Since in your code, you are creating two different objects. So they are different.
Try the follwoing:
public static void main(String[] args)
{
MyClass a = new MyClass(100);
MyClass b= a;
if(a.equals(b))
System.out.println("objects have the same value");
else
System.out.println("objects have different values");
}

Hope this helps.
qionghua
 
Sandeep Nachane
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sai,
I had posted this answer few days back but could not locate it.. hence giving it here again. Hope it will help you.
All classes extend Object class, directly or indirectly and therefore inherit Object's methods. The equals() method is one of these inherited method. Unless you override
equals() method in your class , you get default implementation of equals(). This default implementation assumes that an object is equal to itself. i.e It compares object references for equality, returning true if they have same
value or else would return false if the references have different values.
If you need to look at more self review questions on this topic, you may visit my homepages at http://www.tipsmart.com/javacert/selfreview/objequiv.htm
Sandeep Nachane
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic