user3815954
user3815954

Reputation:

How to implement one method with different argument types?

I should implement a four method to handle one specific objective for different types. I couldnot find a logical way how to implement it. At below code, should I create a abstract and extend relationship or just put them into one class and use method overriding ?

What do I want to manage is that just call(argument). Internally, below methods should be called:

call foo(String argument) if argument is in type of String

call foo(Map argument) if argument is in type of Map

call foo(Integer[] argument) if argument is in type of Array of Integer

Upvotes: 1

Views: 170

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201409

IF there is a mechanism to check type of argument like if type(argument) == String , I will use generic method.

If I understand you, then yes - there is instanceof.

public static <T> void myMethod(T obj) { // <-- generic type T
  if (obj instanceof String) {
    System.out.println("Printing String directly: " + (String) obj);
  } else {
    System.out.println("Printin String by toString(): " + obj.toString());
  }
}

public static void main(String[] args) {
  myMethod("Hello");
  myMethod(new Date());
}

Per the Java Tutorial link,

The instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.

You don't really need generics here, so you might implement myMethod() like

public static void myMethod(Object obj) { // Any Object
  if (obj instanceof String) {
    System.out.println("Printing String directly: " + (String) obj);
  } else {
    System.out.println("Printin String by toString(): " + obj.toString());
  }
}

Finally, all of this distracts from the problem at hand - you should probably just use function overloading as in this answer from laune.

Upvotes: 2

laune
laune

Reputation: 31290

This is a simple case of overloading. Just fill in the method bodies,

void foo(String argument){
}

void foo(Map argument){
}

void foo(Integer[] argument){
}

and a call like

obj.foo( something );

will work, depending on something being one of the three parameter classes.

(Of course, this works with static methods, too.)

Upvotes: 3

Related Questions