简体   繁体   中英

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!

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

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!");
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM