| Author |
getSource method and object comparison
|
Andrew Symantec
Greenhorn
Joined: Apr 24, 2003
Posts: 15
|
|
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
Joined: Oct 18, 2000
Posts: 4121
|
|
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 ]
|
-Nate
Write once, run anywhere, because there's nowhere to hide! - /. A.C.
|
 |
Andrew Symantec
Greenhorn
Joined: Apr 24, 2003
Posts: 15
|
|
Thanks Nathan. [ August 09, 2003: Message edited by: Andrew Symantec ]
|
 |
 |
|
|
subject: getSource method and object comparison
|
|
|