Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

instancing subinterface problem

Status
Not open for further replies.

almoes

Programmer
Jan 8, 2003
291
US
Hi all!

If I have an interface1 which extends interface2, and then I have a method which provides me with an event which delivers me interface2, how can I retrieve an instance to interface1? I hope its not too confusing :-S thanxs

cheers,
alej
 
Well, actually any interface2 object reference can be assigned to an interface1 object reference, because interface2 extends interface1.

Now, Why do you want to cast interface2 to interface1 if interface2 can do everything interface1 does and even more?

Anyway, here's an example

Code:
//First interface
interface Interface1{
    public void sayYes();
}

//Second interface extends first interface
interface Interface2 extends Interface1{
    public void sayNo();
}

//This class implements interface2 and because it extends from interface1 also implements this one
class Implementation implements Interface2{
    public void sayNo() {
        System.out.println("No");
    }

    public void sayYes() {
        System.out.println("Yes");
    }

}

/*This class simulates your event, returning an Interface2 instance*/
class EventSimulator{
    public Interface2 getInterface2(){
        return new Implementation();
    }
}

public class Application {

    public static void main(String[] args) {
        EventSimulator event = new EventSimulator();
        //I assign an interface2 to an interface1 object
        Interface1 result = event.getInterface2();
        result.sayYes();
    }
   
}

edalorzo@hotmail.com
 
Hey really cool, i think i was really blind this time!
thanxs,
alej
 
Hi,

I am having some problems here again....
these are my definitions.

Interface Connection
Interface EspecialConnection extends Connection.

I get compilation error if I try:

Connection normalConn= new Connection();
EspecialConnection varConn=normalConn;

any ideas?
thanxs,
alej
 
Sorry, i think i got it:

EspecialConnection varConn=(EspecialConnection)normalConn;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top