a question about inheritance

K

kevin

Hi all:

look this code:

// code begin
public void actionPerformed(ActionEvent e)
{
Object obj = e.getSource();
if (obj == ok); // ok is declared as JButton
// do something
if (obj == cancel); // cancel is declared as JButton
// do something
.......
}

// code ends

My question is why the expression obj == ok and obj == cancel can work
because
they are two different type class, can different class compared with
"==" and why?



thanks!

kevin
 
J

Joona I Palaste

kevin said:
look this code:
// code begin
public void actionPerformed(ActionEvent e)
{
Object obj = e.getSource();
if (obj == ok); // ok is declared as JButton
// do something
if (obj == cancel); // cancel is declared as JButton
// do something
......
}
// code ends
My question is why the expression obj == ok and obj == cancel can work
because
they are two different type class, can different class compared with
"==" and why?

Yes, different classes can be compared, as long as one of them is a
subclass of the other. In your code, one of the classes is Object, and
every other class is a subclass of Object, so it always works.
The reason for this is polymorphism, and the Java type system. Note that
your variables don't actually contain the objects - they contain
references to them. While an object always has the same class, it can
have references of various class types referring to it. The class
itself, any of its superclasses, or any interface it implements.
 
A

Ann

kevin said:
Hi all:

look this code:

// code begin
public void actionPerformed(ActionEvent e)
{
Object obj = e.getSource();
if (obj == ok); // ok is declared as JButton
// do something
if (obj == cancel); // cancel is declared as JButton
// do something
......
}

// code ends

My question is why the expression obj == ok and obj == cancel can work
because
they are two different type class, can different class compared with
"==" and why?

obj is a reference, ok is a reference, cancel is a reference
the jvm determines what a reference looks like, but if two
different references refer to the same object then == yields true
 

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
474,430
Messages
2,571,676
Members
48,796
Latest member
Greg L.

Latest Threads

Top