Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

getSource method and object comparison

 
Andrew Symantec
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • 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 ]
 
Nathan Pruett
Bartender
Posts: 4121
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
Thanks Nathan.
[ August 09, 2003: Message edited by: Andrew Symantec ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic