In a server code, I have a ProtocolHandler class which reads from the socket, finds out which type of packet it's dealing with and dispatches it to the client. I'm trying to have the following architecture:
public interface Packet { //... } public class ClientInformations implements Packet { //... } public class ProtocolHandler { //.... public void bytesReceived(byte[] bytes) { //... Determine the type of the packet Packet packet = determineTypeOfPacketAndRead(bytes); // Here I already have the packet object built, // like ClientInformations@1a1a1a1a[...] client.packetReceived(packet); } //... } public class Client { //... public void packetReceived(Packet pkt) { System.out.println("Unimplemented packet received."); } public void packetReceived(ClientInformations ci) { } //... } (I don't know how to explain it easily with words). The problem is, I really thought packetReceived(ClientInformations) would be called, but it's not. It's calling the more general packetReceived(Packet) method. Am I wrong? How can I still use the same architecture then?
--EDIT
Now I understand why that happens. The problem is, i have other packet classes, such as Movement, Sync, Spawn. I wanted to ease adding new packets by just having to add a new method to the Client class. Isn't there another way of doing that then? I mean, a way to automatically analyse the type of the packet object at runtime and doing the most specific method call?
bytesReceived? I cannot know of which typepacketis, even though you have addedSystem.out.println(packet), I'd rather not focus on that.determineTypeOfPacketAndReadis declared to returnsPacket. Because of that compiler cant link it topacketReceived(ClientInformations ci). You can do it manually by casting result toClientInformationsafter checking its type withinstanceof.