Interface and casting

  • Thread starter Thread starter anon
  • Start date Start date
A

anon

How can I do the following....

interface iface
{
int someMethod();
}

class c1 : iface
{
int someMethod() {return 10;}
}

class c2 : iface
{
int someMethod() {return {return 20;}
}

class Test
{
int testMethod()
{
return testInterface(new c1());
}

int testInterface(iface i)
{
// in this case, returns 10
// as it stands now, i have to
// cast it to a c1, before it will
// return correct value;
return i.testMethod
}
}

Thanks
 
anon said:
How can I do the following....

interface iface
{
int someMethod();
}

class c1 : iface
{
int someMethod() {return 10;}
}

class c2 : iface
{
int someMethod() {return {return 20;}
}

class Test
{
int testMethod()
{
return testInterface(new c1());
}

int testInterface(iface i)
{
// in this case, returns 10
// as it stands now, i have to
// cast it to a c1, before it will
// return correct value;
return i.testMethod
}
}

Firstly, please post code which will compile - the above won't compile
for various reasons, which makes it difficult to tell what you actually
want to happen. Casting i to a c1 won't help at all, as neither iface
nor c1 declare a method testMethod. The two implementations of
someMethod also need to be public.
 
anon said:
How can I do the following....

interface iface
{
int someMethod();
}

class c1 : iface
{
int someMethod() {return 10;}
}

class c2 : iface
{
int someMethod() {return {return 20;}
}

class Test
{
int testMethod()
{
return testInterface(new c1());
}

int testInterface(iface i)
{
// in this case, returns 10
// as it stands now, i have to
// cast it to a c1, before it will
// return correct value;
return i.testMethod
}
}


The only thing you can do in this case is call someMethod() on i:

int testInterface(iface i)
{
return i.someMethod();
}

because testMethod is not a member of iface. If you wanted to call
testMethod you would have to add it to iface and then add it to c1 and c2.

I don't believe you would want to cast i to c1 in testInterface. That's
because as soon as you passed a c2 or other iface derived type, you would
get an InvalidCastException.

Joe
 
I'm sorry Joe,

I made some mistakes when i originally posted.. please
see my new post ( interface and casting (second try) )

Thanks
Kurt
 
Back
Top