Edmondo
Edmondo

Reputation: 20090

Why does SSLSocketFactory.createSocket returns a Socket instead of SSLSocket?

In my code according to a boolean flag I should decide whether or not to handshake an SSL socket. I use the SSLSocketFactory to create the socket, and this is the signature of the createSocket method taken from the official Javadoc.

abstract Socket createSocket(Socket s, String host, int port, boolean autoClose)

It appears a clear design choice here to return a Socket and not an SSLSocket, that means that classes using this method wouldn't need to know that the Socket is an SSLSocket.

However, if I have to handshake it, I have to downcast it, because the method

  public abstract void startHandshake() throws java.io.IOException;

is defined on the SSLSocket class.

SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket( getApiServerAddress(), getPort() );

Which of the three possible answers is correct?

Upvotes: 1

Views: 2598

Answers (1)

boky
boky

Reputation: 835

Because createSocket method is inherited from SocketFactory. It's impossible to override result type.

There could be a way around it using generics, but that would break existing API and all existing code.

Upvotes: 3

Related Questions