Tenman Rogers
Tenman Rogers

Reputation: 3

Same method called with different objects as parameter

I have a program that sends requests to a server. There are many different types of request, and each has their own class. For example, I have a checkServerOnlineRequest which sends a short message to the server, or a getAmountOfGoldRequest which sends a very different message.

class CheckServerOnlineReq{
    static final byte requestID = 1;
    byte[] message;

    void setMessage(byte messageNumber){
        message = new byte[2];
        message[0] = messageNumber;
        message[1] = requestID;
    }
}

To send the requests, I have a Client class. It has static method called send which I would like to accept any type of request (i.e. a number of different classes)

My question is, how can I set up send()'s parameters to allow any type of request to be given as an argument.

Upvotes: 0

Views: 1757

Answers (3)

Matsemann
Matsemann

Reputation: 21844

Make all requests subclass/implement a Request-class/interface, and make your send method have Request as argument.

E.g. class CheckServerOnlineReq extends/implements Request..

send(Request request)

Upvotes: 1

NPE
NPE

Reputation: 500903

The canonical way is to declare an interface, and make the concrete request classes implement that interface:

public interface IRequest { ... }

public class CheckServerOnlineRequest implements IRequest { ... }
public class GetAmountOfGoldRequest implements IRequest { ... }

Then the send() method can accept IRequest as its argument.

public static void send(IRequest request) { ... }

Upvotes: 1

hvgotcodes
hvgotcodes

Reputation: 120318

All of your request classes should extend from a base Request class, that you define. Your static method should take an argument of Request request. Your base Request class (possibly abstract, possibly implementing an interface -- the details depend on what exactly is going on) should define all the methods Requests use, regardless of the actual type of the Request.

Failing that, your send method could take argument of the type Object, but that would be really bad, as you would only be able to access Object methods without casting.

Upvotes: 1

Related Questions