• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

equals for class objects

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • 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
  • 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
 
Why am I so drawn to cherry pie? I can't seem to stop. Save me tiny ad!
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    Bookmark Topic Watch Topic
  • New Topic