• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

One Question

 
Yojana
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This program running perfectly but I am unable to understand the
program. Please anybody help me.
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 values");
else
System.out.println("Objects have different values");
}
}
 
Herbert Maosa
Ranch Hand
Posts: 289
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yojana,
could you please state what it is that you do not understand about the program, so people can you assist you in context ?
Herbert
 
Yojana
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Herbert!
According to me it should print "Objects have the same values" but it is printing "Objects have different values" why?
regards
Yojana

 
Surya B
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Yojana,
The equals method which is used here is the equals method of the Object class,which is the root of the class hierarchy.All objects, including arrays, implement the methods of this class.So that is the main reason the compiler didn't flag an error in the first place when you used the equals method,though it was not defined in your class.So when you use equals in your code you are basically calling the Object class equals method which indicates whether some other object is "equal to" this one.In your case a,b are two different handles of the class MyClass and thats the main reason why it prints out "Objects have different values".If you want to print out "Objects have the same values" then you shoud override the equals method of the Object class.The class String also overrides the equals method of the Object class to implment its version.Hope my explanation is clear.
Surya

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic