Cast a superclass type to a subclass type?

102 views Asked by At

I know that multiple questions have been asked about this, but none of them suit my needs. So sorry about that.

Anyways, my class AdvancedSocket extends java.net.Socket. In my class AdvancedServerServer extends java.net.ServerSocket. So, in AdvancedServerSocket, I override the accept() method to return an AdvancedSocket. Here is that method:

@Override
public AdvancedSocket accept() throws IOException {
    return (AdvancedSocket) super.accept();
}

But this throws a java.lang.ClassCastException.

3

There are 3 answers

2
AudioBubble On

in fact your accept method still returns usual socket (because you return super.accept()), how do you think it can be casted? You need convert it manually (build advanced socket on top of usual socket)

0
Mapsy On

AdvancedServerSocket is not a type of AdvancedSocket, therefore it can't be done.

There must be somewhere in between where it seems logical to treat them the same, so you should be able to create an interface which defines this functionality and have both classes implement it. Then you'll be able to handle them in the same generic manner.

4
user1675642 On

When you call super.accept() the code in SocketServer's accept() method is executed. That class knows nothing about the AdvancedSocket class you have defined, so whatever it returns, it won't be an instance of AdvancedSocket.

If you want to return an AdvancedSocket, you could take the Socket instance returned by the call to super.accept() and make an AdvancedSocket out of it.

I hope that helps.