Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java interface with different method parameters

Tags:

java

interface

I want to have an interface that allows me to use methods with different parameters. Suppose I have an interface:

public interface Stuff {
    public int Add();
 }

And I have two classes A and B who implement the interface.

public class CLASS A implements Stuff{
    public int Add(int id);
}  


public class CLASS B implements Stuff{
    public int Add(String name);
}

How can I achieve this?

like image 548
fredjohnson Avatar asked Nov 29 '22 22:11

fredjohnson


1 Answers

You can write a generic interface for adding some type, something like this:

public interface Addable<T> {
    public int add(T value);
}

and then implement it via

public class ClassA implements Addable<Integer> {
    public int add(Integer value) {
        ...
    }
}

public class ClassB implements Addable<String> {
    public int add(String value) {
        ...
    }
}
like image 104
khelwood Avatar answered Dec 21 '22 11:12

khelwood