• 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

getSource method and object comparison

 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi all, I have a question troubled me for long time.
Too often, in Swing we can see statements like this:
JButton button1 = new JButton();
JButton button2 = new JButton();
.......
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if ( source == button1)
{
........
}
}
The problem is, the type of source is Object, the type of button1 is JButton, how can they do a equality comparison? For two objects, normaly if they have same object type, they can compare for quality.
Can someone help me out?
Thanks
[ August 09, 2003: Message edited by: Andrew Symantec ]
 
Bartender
Posts: 4121
IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Because == tests the equality of the reference, not the equality of the object data (that is what .equals() is for). The only way == is going to return true on test of two object references is if both are simply different references to the same object.



In this case s1 == s2 returns true, but s1 == s3 returns false. They have equivalent data, but reference different objects. s1.equals( s2 ) and s1.equals( s3 ) both return true, because .equals() tests data equivalence.
[ August 09, 2003: Message edited by: Nathan Pruett ]
 
Andrew Symantec
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Nathan.
[ August 09, 2003: Message edited by: Andrew Symantec ]
 
Alas, poor Yorick, he knew this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic