I want to declare a variable that contains a class that implements a specific interface. In particular, I am trying to keep SocketChannelit DatagramChannelin the same property so that I can use them interchangeably. Both of these classes extend SelectableChannelas well as implement ByteChannel, and I want to call methods from both. I do not want to store this in two separate variables, because I have to be the same object. I want to pass this object to a single variable in the constructor.
Is it possible to do this? If not, what are the common workarounds that still support this type of model? For clarity, here are the (incorrect) declarations that might describe what I'm trying to do, whether they were valid:
private SelectableChannel & ByteChannel byteChannel;
private SelectableChannel implements ByteChannel byteChannel;
private? extends SelectableChannel implements ByteChannel byteChannel;
Note:
I am not looking for other ways to deal with networks that avoid this problem or other ways to implement networks. This question is how to declare a variable to hold a subclass of a class that also implements a specific interface. I just gave the specifics so that you know that I cannot create a new interface or subclass, because in this case all the classes involved are part of the package java.nio.
source
share