File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes equals for class objects Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Professional Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "equals for class objects" Watch "equals for class objects" New topic
Author

equals for class objects

devi nachimuthu
Greenhorn

Joined: Jan 07, 2003
Posts: 10
1: class MyClass
2: {
3: static int maxElements;
4:
5: MyClass(int maxElements)
6: {
7: this.maxElements = maxElements;
8: }
9:
10: }
11:
12: public class Q19
13: {
14: public static void main(String [] args)
15: {
16:
17: MyClass a = new MyClass(100);
18: MyClass b = new MyClass(100);
19:
20: if (a.equals(b))
21: System.out.println("objects are same");
22: else
23: System.out.println("objects are different");
24: }
25: }
a) compilation error at line 20. equals() method was not defined.
b) compiles fine, runtime exception at line 20
c) prints "objects are same"
d) prints "objects are different"
My answer is c. But the given answer is d, why is it...? Can somebody explain me this...?
Thanks
Ajith Kallambella
Sheriff

Joined: Mar 17, 2000
Posts: 5781
Since your class MyClass doesn't override the equals method defined on the Object class, what gets printed is actually the result of calling equals method on the Object class which does plain reference comparison. Hence the result.
Ajith


Open Group Certified Master IT Architect.
Sun Certified Architect(SCEA).
 
 
subject: equals for class objects
 
Threads others viewed
Constructor doubt
Can someone explain this to me?
Objects
equals() fails here
equals()
IntelliJ Java IDE