I am extending the class Java.net.DatagramSocket
and giving the subclass its own constructor. The constructor for my new class, UDP_Socket
, is as follows
private UDP_Socket(int port) throws IOException {
super(null); // Creates an unbound socket.
super.setReuseAddress(true); // You set reuse before binding.
super.bind(new InetSocketAddress(port)); // finally, bind
}
The only problem is on the line super(null)
, I am getting ambiguous reference to both constructor DatagramSocket(DatagramSocketImpl) and DatagramSocket(SocketAddress)
. I need the super(null)
line to create an unbound socket and I believe that I am supposed to set the reuse address socket option before binding. How do I fix this error?
The problem is because you call super(null)
is valid parameter to both DatagramSocket(DatagramSocketImpl)
and DatagramSocket(SocketAddress)
.
So, the compiler is confused. You can call only one of the constructors.
Use,
super((DatagramSocketImpl) null);
or,
super((SocketAddress) null);
depending on which constructor you want to call.
The error:
ambiguous reference to both constructor DatagramSocket(DatagramSocketImpl) and DatagramSocket(SocketAddress)
Is telling you that null
can reference (DatagramSocketImpl) null
or (SocketAddress) null
thus making it ambiguous.
You must explicitly call one of the two constructors
// super((DatagramSocketImpl) null)
super((SocketAddress) null)
or have your constructor require that
private UDP_Socket(int port, SocketAddress addr) throws IOException {
super(addr);
Edit:
Code from: Class DatagramSocket
private DatagramSocket getDatagramSocket (int port) {
DatagramSocket s = new DatagramSocket(null);
s.setReuseAddress(true);
s.bind(new InetSocketAddress(port));
return s;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.