hackingsacks
hackingsacks

Reputation: 13

Is there a clean way of defining a Java interface method that has different parameters for each implementation class?

For example, say I have an interface that defines the method action(...) and I have three (in reality way more) classes that implement action with different parameters like so:

public class Class1 implements SomeInterface {
    public int action(int num) { ... }
}

public class Class2 implements SomeInterface {
    public String action(String string) { ... }
}

public class Class3 implements SomeInterface {
    public double action(double dub) { ... }
}

I feel like this isn't possible, but there's got to be some way to tell the user that each of these classes have an action method; maybe there's a way for it to dynamically accept arguments?

EDIT: What if we don't know that there is exactly one parameter? For example, is something like this possible?

interface SomeInterface<T, T, ..., T> {
    T action(T t1, S s, ..., U u);
}

I feel like this is a really strange question, so I'll try to provide some more context. I'm working on a card game where there are different Action Cards that do different things, and require different information. I thought an Action Card interface was in order here, but then I ran into the issue of how to specify action when each implementation class needs totally different parameters and a different number of parameters as opposed to them implementing the exact same method differently or them each requiring the same number of parameters. For this reason, it is my understanding that generics won't work here but maybe I'm wrong or there's a better way of doing this altogether; perhaps the interface was the wrong way to do it from the start?

Upvotes: 0

Views: 1149

Answers (1)

Robby Cornelissen
Robby Cornelissen

Reputation: 97130

You can use generics:

interface SomeInterface<T> {
    T action(T t);
}

class Class1 implements SomeInterface<Integer> {
    public Integer action(Integer i) { return null; }
}

class Class2 implements SomeInterface<String> {
    public String action(String s){ return null; }
}

class Class3 implements SomeInterface<Double> {
    public Double action(Double d) { return null; }
}

Generics can only be used for object types, so you have to use primitive wrappers instead of primitives.

Upvotes: 4

Related Questions