• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Why???

 
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class B {
static int x;
public boolean equals(Object obj){
if (obj instanceof B) {
B a = (B) obj;
return (this.x == a.x);
}
else return false;
}
public static void main(String[] args) {
B a = new B(); a.x =23;
B a1 = new B(); a1.x=0;
System.out.println(a.equals(a1));
}
}

Why this returns true
 
Ranch Hand
Posts: 284
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well it returns true cause of the following lines-:
At line equals(a1) you pass equals(Object obj) obj as B instance only(a1).
So your instance-of test (if (obj instanceof B)) is true.
Now you lines-
B a = (B) obj;
makes a points to a1 only and thus makes the values of a.x equal to a1.x. So we get true in return (this.x == a.x);.
Hope this clears
 
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I've added some statements to the original code,



The above code will generate output :


After a.x = 23 statement
a.x = 23
a1.x = 23

After a1.x = 0 statement
a.x = 0
a1.x = 0
true



x is static(class) variable, so there will be only one copy of x which will be shared by all the objects of class B. So it doesn't matter if you access x using any objects reference variable, it will be same as B.x.
Here, equals() test will always be true for all the objects of class B.

hth.
[ March 16, 2008: Message edited by: Khushbu Ghodasara ]
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic