instanceof question

Discussion in 'Java' started by Dotty, Feb 16, 2005.

  1. Dotty

    Dotty Guest

    This question came up as a result of my reading
    a news message about instanceof. Below is my code,
    how does java know that "src" is a JButton?
    ----
    public void actionPerformed(ActionEvent e)
    {
    Object src = e.getSource(); // get action source
    if (src == DynamicPanel.dynamicResetButton)
    {
    // do stuff
    return;
    }
    // other stuff
    }
    Dotty, Feb 16, 2005
    #1
    1. Advertising

  2. Dotty

    Guest

    src is a reference to the object that caused the event to occur.
    Recall that when the == operator is used between object references, it
    tests to see if the references point to the same object in memory.

    So what's happening is you're asking is the Object that src refers to
    the same object that dynamicResetButton refers to.
    , Feb 16, 2005
    #2
    1. Advertising

  3. Dotty

    dar7yl Guest

    "Dotty" <> wrote in message
    news:eek:...
    > This question came up as a result of my reading
    > a news message about instanceof. Below is my code,
    > how does java know that "src" is a JButton?
    > ----
    > public void actionPerformed(ActionEvent e)
    > {
    > Object src = e.getSource(); // get action source
    > if (src == DynamicPanel.dynamicResetButton)
    > {
    > // do stuff
    > return;
    > }
    > // other stuff
    > }


    It doesn't. Java doesn't know anything about an object.
    It is merely a language. No smarts there. The programmer
    may know, and impart his wisdom in the code.

    In this context, you don't care that src is a JButton.
    You are just comparing the object "src" with the object
    "DynamicPanel.dynamicResetButton". If they are equal,
    ie, the same object, it will execute the context // do stuff...
    Here, if you wish, you may cast src to JButton, but you
    could test with instanceof to be absolutely sure. (If, for
    instance, someone else had changed the type of
    dynamicResetButton)

    regards,
    Dar7yl
    dar7yl, Feb 16, 2005
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Paul Tomblin

    Re: Dumb instanceof question

    Paul Tomblin, Jul 11, 2003, in forum: Java
    Replies:
    35
    Views:
    1,203
    Manish Jethani
    Jul 27, 2003
  2. WillieLWZ
    Replies:
    8
    Views:
    433
    WillieLWZ
    Feb 23, 2006
  3. Replies:
    14
    Views:
    2,797
    Chris Uppal
    May 2, 2006
  4. Replies:
    21
    Views:
    21,301
  5. System Administrator
    Replies:
    1
    Views:
    92
    Richard Cornford
    Mar 11, 2007
Loading...

Share This Page