• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Rob Spoor
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Henry Wong
  • Liutauras Vilda
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Tim Holloway
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Mikalai Zaikin
  • Piet Souris

equals for class objects

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
reply
    Bookmark Topic Watch Topic
  • New Topic