4

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?

ΦXocę 웃 Пepeúpa ツ
48.4k17 gold badges77 silver badges102 bronze badges
asked May 23, 2017 at 8:19

3 Answers 3

15

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) {
 ...
 }
}
answered May 23, 2017 at 8:22
Sign up to request clarification or add additional context in comments.

2 Comments

How do you call this polymorphically
@station Same way you'd call anything else polymorphically.
6

either overload the methods:

public interface Stuff {
 public int add(String a);
 public int add(int a);
 }

or check something in common in the inheritance

public interface Stuff {
 public int add(Object a);
 }

or use generics

public interface Stuff<T> {
 public int add(T a);
 }
answered May 23, 2017 at 8:21

1 Comment

Both options is usable but personally i would prefer generics.
0

you need to override the method

public class CLASS A implements Stuff{
 public int add(int a ,int b){
 int result=a+b;
 return result;
 }
 public static void main(String[] args) {
 // TODO Auto-generated method stub
 A ab=new A();
 ab.add(3, 4);
 System.out.println(ab.add(3, 4));
 }
}

Is this you want?

answered May 23, 2017 at 8:42

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.