Ziv*_*eor 2 java class function
我的意思是这样的:
function f(int a) {
}
function f(double a) {
}
function f(string a) {
}
我想要一个可以使用相同的名称(调用的函数f)和相同的变量的名称(a),但不一样的类型(int,double等等)
谢谢!
你正在寻找泛型:
实例方法:
public <T> void f(T a) { // T can be any type
    System.out.println(a); // test to see  `a` is printed
   // Do something..
}
类方法:
public static <T> void f(T a) { // T can be any type
    System.out.println(a); // test to see  `a` is printed
    // Do something..
}
假设这是在你的main方法中,你可以像这样调用类方法:
例1:
int number = 10;
f(number);
例2:
String str = "hello world";
f(str);
例3:
char myChar = 'H';
f(myChar);
例4:
double floatNumber = 10.00;
f(floatNumber);
和任何其他类型.
进一步阅读泛型.