dimanche 20 février 2022

What to do in Java instead of calling a subclass constructor?

I'm writing a class to represent a protocol packet, and one of the header fields indicates which packet subtype it is — let's say the two subtypes are Foo and Bar. So I'd like to have a class hierarchy of:

MyPacket MyFooPacket MyBarPacket

There's a MyPacket constructor that takes a String representing te encoded packet and starts decoding it, storing each decoded fields in a MyPacket attribute, and after all the common fields are done and we know whether it's a MyFooPacket or a MyBarPacket, I'd like to then turn this MyPacket into a MyFooPacket or MyBarPacket and leave it up to the subclass' constructor to store the remaining fields in subclass attributes. But I see this isn't possible in Java.

What am I supposed to do instead?

Aucun commentaire:

Enregistrer un commentaire