When an application contains just one version of a method, you can call the method using a parameter of the correct data type or one that can be promoted to the correct data type. For example, you can call a method which needs double variable datatype use int value, but not allowed versa vice.
publicstaticvoid simpleMethod(double d){
System.out.println("Method receives double parameter "+d);
}
publicstaticvoid main(String[] args){
Test2.simpleMethod(1.00);
Test2.simpleMethod(1);
}
Output:
Method receives double parameter 1.0
Method receives double parameter 1.0
publicstaticvoid simpleMethod(double d){
System.out.println("Method receives double parameter "+d);
}
publicstaticvoid simpleMethod(int i){
System.out.println("Method receives int parameter "+i);
}
publicstaticvoid main(String[] args){
Test2.simpleMethod(1.00);
Test2.simpleMethod(1);
}
Output:
Method receives double parameter 1.0
Method receives int parameter 1
本文介绍了Java中如何调用只有一个版本的方法,并通过参数类型转换实现不同数据类型的传递。当方法期望接收double类型参数时,可以接受int类型作为输入,并自动将其提升为double类型。但反之则不可行。此外,当存在多个方法重载时,Java会根据参数类型选择合适的方法。
1564

被折叠的 条评论
为什么被折叠?



