Michael:
I would certainly rather not create a huge if/else block since I have about 150-200 MsgXXX classes! This also sort of defeats the purpose of inheritance. I have a parent class which I know is a child!
With regards to casting, the rule is that you can't cast down unless what you're casting was originally something further down. For instance:
I believe I have all that correct -- I'm not near a compiler so I can't check it, but that's the grasp I have of things now.
One solution I have thought up is the following, but it strikes me as an inelegant solution:
instead of:
I could do:
Since casting up is automatic, that means I could do:
but this introduces other subtle problems that are too long to explain without showing you all of my code. However, those problems are minor, so it is a *workable* solution, but I am convinced there is some more elegant and correct way to do this. Perhaps I need to restructure my classes somehow, but I feel like I'm missing something basic...
Maulin:
What do you get when you try to do,
System.out.println("Message type:"+msg.getClass().getName()); after line,
BasicMessage msg = myDevice.readMessage();
If that returns you MsgFoo you MUST be able to cast it to MsgFoo...
Although I haven't tried it, I am certain that the message type will be BasicMessage. The code inside readMessage looks like this:
which means that anytime I call:
I am bound to get a bonafide BasicMessage back. My problem is that I thought I could do:
but I can't, because the value returned from readMessage was never a MsgFoo to begin with, so I can't cast down from BasicMessage.
Still frustrated.... I have the sneaking feeling that this is what generics (AKA C++'s "templates") are intended to solve and I'm stuck.
Please tell your friends to take a look at this if you're stumped, I really need to figure this out to get my code working and this is all that is stopping my project from progressing right now!
Thanks again for all of the input, and TIA for those now joining in...
Idan