O
Oliver Wong
Let's say I have these two interfaces and these two classes:
<code>
public interface IOne {
public void methodOne();
}
public interface ITwo {
public void methodTwo();
}
public class A implements IOne, ITwo {
/*Implementation of the methods here*/
}
public class B implements IOne, ITwo {
/*Implementation of the methods here*/
}
</code>
And now I have code, for which either A or B would do the job fine, or even
some as of yet unknown class C, as long as it implements the IOne and ITwo
interfaces.
That is, I'd like to declare a reference as being of type IOne and ITwo at
the same time: something like:
<code>
private int myCode(IOne ITwo myVar, int someParam) {
myVar.methodOne();
myVar.methodTwo();
return someParam;
}
</code>
Assume that classes A and B come from third parties, so I can't just invent
a new interface IOneAndTwo, and have A and B implement those. All the
solutions I can come up with are a bit messy.
<code>
private int myCode(IOne myVar, int someParam) {
if (!(myVar instanceof ITwo)) {
throw new IllegalArgumentException("myVar has to implement ITwo");
}
myVar.methodOne();
((ITwo)myVar).methodTwo();
return someParam;
}
</code>
<code>
private int myCode(IOne myVar1, ITwo myVar2 int someParam) {
if (myVar1 != myVar2) {
throw new IllegalArgumentException("myVar1 and myVar2 must refer to the
same object");
}
myVar1.methodOne();
myVar2.methodTwo();
return someParam;
}
</code>
etc.
Any ideas on how to declare (or simulate) a multiple-interface-type
reference?
- Oliver
<code>
public interface IOne {
public void methodOne();
}
public interface ITwo {
public void methodTwo();
}
public class A implements IOne, ITwo {
/*Implementation of the methods here*/
}
public class B implements IOne, ITwo {
/*Implementation of the methods here*/
}
</code>
And now I have code, for which either A or B would do the job fine, or even
some as of yet unknown class C, as long as it implements the IOne and ITwo
interfaces.
That is, I'd like to declare a reference as being of type IOne and ITwo at
the same time: something like:
<code>
private int myCode(IOne ITwo myVar, int someParam) {
myVar.methodOne();
myVar.methodTwo();
return someParam;
}
</code>
Assume that classes A and B come from third parties, so I can't just invent
a new interface IOneAndTwo, and have A and B implement those. All the
solutions I can come up with are a bit messy.
<code>
private int myCode(IOne myVar, int someParam) {
if (!(myVar instanceof ITwo)) {
throw new IllegalArgumentException("myVar has to implement ITwo");
}
myVar.methodOne();
((ITwo)myVar).methodTwo();
return someParam;
}
</code>
<code>
private int myCode(IOne myVar1, ITwo myVar2 int someParam) {
if (myVar1 != myVar2) {
throw new IllegalArgumentException("myVar1 and myVar2 must refer to the
same object");
}
myVar1.methodOne();
myVar2.methodTwo();
return someParam;
}
</code>
etc.
Any ideas on how to declare (or simulate) a multiple-interface-type
reference?
- Oliver