I have this method:
private Message getMessage(DataInputStream in) throws IOException {
CommandEnum caption = CommandEnum.valueOf(in.readUTF());
BasicMessage inputMessage;
if (caption.equals(CommandEnum.BEGIN) || caption.equals(CommandEnum.FILEADDRESS)
|| caption.equals(CommandEnum.CONTAINNAMESERVER))
inputMessage = new AddressMessage(caption,in.readUTF(),in.readInt());
if (caption.equals(CommandEnum.CONTAINFILE) || caption.equals(CommandEnum.DONTCONTAINFILE)
|| caption.equals(CommandEnum.WANTFILE))
inputMessage = new FileMessage(caption,in.readUTF());
else
inputMessage = new BasicMessage(caption);
in.readUTF();
return inputMessage;
}
The signature states that the method return Message, an object I’ve created. Notice that in some cases it returns AddressMessage, another object of mine that extends Message.
My problem – in case i return new AddressMessage(arguments) I can’t downcast it later to
be an AddressMessage object [writing (AddressMessage) object]
I agree, if what you have is an AddressMessage, then it can be always be downcasted as such.
What I expect is more a logic mistake. That you actually try to downcast an instance of another class. Just try to debug that place or print
obj.getClass()just to verify what class you are actually trying to downcast.You can also use
if (my_message instanceof AddressMessage) ...or something like this.