There is no way in Java to declare the variable the way you would like to do it.
You could use SelectableChannel
for the type of the variable (since this is a supertype of both SocketChannel
and DatagramChannel
), and cast it to a ByteChannel
whenever you need to call methods from that interface. Simple example:
class MyClass {
private SelectableChannel channel; // either a SocketChannel or a DatagramChannel
public int readStuff(ByteBuffer buffer) {
// Cast it to a ByteChannel when necessary
return ((ByteChannel) channel).read(buffer);
}
}
(Or the other way around: declare the variable as a ByteChannel
and cast to a SelectableChannel
when necessary - whichever is more convenient in your case).