Can you cast an object to one that implements an interface? (JAVA)

Posted by DDP on Stack Overflow See other posts from Stack Overflow or by DDP
Published on 2010-06-07T03:37:57Z Indexed on 2010/06/07 3:42 UTC
Read the original article Hit count: 289

Filed under:
|
|
|
|

Can you cast an object to one that implements an interface? Right now, I'm building a GUI, and I don't want to rewrite the Confirm/Cancel code (A confirmation pop-up) over and over again.

So, what I'm trying to do is write a class that gets passed the class it's used in and tells the class whether or not the user pressed Confirm or Cancel. The class always implements a certain interface.

Code:

class ConfirmFrame extends JFrame implements ActionListener
{
    JButton confirm = new JButton("Confirm");
    JButton cancel = new JButton("Cancel");
    Object o;

    public ConfirmFrame(Object o)
    {
        // Irrelevant code here
        add(confirm);
        add(cancel);
        this.o = (/*What goes here?*/)o;
    }

    public void actionPerformed( ActionEvent evt)
    {
        o.actionPerformed(evt);
    }
}

I realize that I'm probably over-complicating things, but now that I've run across this, I really want to know if you can cast an object to another object that implements a certain interface.

© Stack Overflow or respective owner

Related posts about java

Related posts about gui