instanceof question

D

Dotty

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
}
 
K

klynn47

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.
 
D

dar7yl

Dotty said:
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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top