参数重载时的类型自动提升

今天重读think in java 看到参数重载时类型的自动提升,记录一下

 

当传入常数时,会被当作int处理,例如:

public class Test { void f(char i){System.out.println("arg is char!");}; void f(byte i){System.out.println("arg is byte!");}; void f(short i){System.out.println("arg is short!");}; void f(int i){System.out.println("arg is int!");}; void f(long i){System.out.println("arg is long!");}; void f(float i){System.out.println("arg is float!");}; void f(double i){System.out.println("arg is double!");}; public static void main(String[] args) { // TODO Auto-generated method stub Test t = new Test(); t.f(5); } }   

结果会是 arg is int!

 

那如果没有int形式的参数呢?重载类型会自动提高,例如:

public class Test { void f(char i){System.out.println("arg is char!");}; void f(byte i){System.out.println("arg is byte!");}; void f(short i){System.out.println("arg is short!");}; //void f(int i){System.out.println("arg is int!");}; void f(long i){System.out.println("arg is long!");}; void f(float i){System.out.println("arg is float!");}; void f(double i){System.out.println("arg is double!");}; public static void main(String[] args) { // TODO Auto-generated method stub Test t = new Test(); t.f(5); } }

结果会是 arg is long!

 

其他情况类似,会一直提升类型直到能匹配到为止,例如从byte提高到了double:

public class Test { void f(char i){System.out.println("arg is char!");}; //void f(byte i){System.out.println("arg is byte!");}; //void f(short i){System.out.println("arg is short!");}; //void f(int i){System.out.println("arg is int!");}; //void f(long i){System.out.println("arg is long!");}; //void f(float i){System.out.println("arg is float!");}; void f(double i){System.out.println("arg is double!");}; public static void main(String[] args) { // TODO Auto-generated method stub byte x = 0; Test t = new Test(); t.f(x); } }

结果会是 arg is double!

 

char比较特殊,如果匹配不到会提升至int,如果还匹配不到则继续提升。

 

 

 

那如果传入参数的类型大于形参呢?

答案是编译器会告诉你此路不通  :)

 

你可能感兴趣的:(参数重载时的类型自动提升)