Ziv Sdeor
Ziv Sdeor

Reputation: 33

How do I create a function in Java, that can be called with many types?

what I mean is something like this:

function f(int a) {

}
function f(double a) {

}
function f(string a) {

}

I want to make a function that can be called with the same name (f) and the same variable's names (a), but not the same types (int, double etc.)

THANKS!

Upvotes: 2

Views: 669

Answers (2)

Ousmane D.
Ousmane D.

Reputation: 56469

You're looking for generics:

instance method:

public <T> void f(T a) { // T can be any type
    System.out.println(a); // test to see  `a` is printed
   // Do something..
}

class method:

public static <T> void f(T a) { // T can be any type
    System.out.println(a); // test to see  `a` is printed
    // Do something..
}

Assuming this is inside your main method, you can call the class method like so:

Example 1:

int number = 10;
f(number);

Example 2:

String str = "hello world";
f(str);

Example 3:

char myChar = 'H';
f(myChar);

Example 4:

double floatNumber = 10.00;
f(floatNumber);

and any other type.

Further reading of Generics.

Java Documentation of Generics

Upvotes: 5

Graytr
Graytr

Reputation: 104

Java classes can have methods of the same name, but different parameter types, just like you're asking for.

public class Foo {

    public void f(int a){
        System.out.println(a);
    }

    public void f(double a){
        System.out.println(a);
    }

    public void f(String a){
        System.out.println(a);
    }

    public static void main(String[] args) throws InterruptedException{
        Foo f = new Foo();
        f.f(9.0);
        f.f(3);
        f.f("Hello world!");
    }

}

Upvotes: 3

Related Questions