加宽、装箱、var-arg

优先原则:加宽优先于装箱优先于var-arg(加宽->装箱->var-arg)
         不能先加宽,后装箱(int不能变成Long)。

            可以先装箱,后加宽(int可以通过Integer变成Object)

         不能从一种包装器类型加宽的另一种包装器类型

加宽一个基本变量是合法的,在每一种情况下,当未找到精确的匹配时,JVM就会使用一个方法,他带有比形参更宽的最小实参

Java5的设计者决定:最重要的规则应该是已有的代码应该像他们过去那样运行。Java 5's designers decided that the most important rule should be that pre-existing code should function the way it used to。即使每个调用都需要某种转换,编译器仍将优先选择较旧的风格,从而保持现有代码的健壮性。var-arg方法比其他方法“更宽松”。

加宽引用变量

这里的关键点是:引用变量加宽依赖于继承。换句话说,依赖于IS-A测试。因此,从一个包装器类加宽到另一个包装器类是非法的。因为包装器类之间是平等的。例如,Short IS-A Integer这种说法是无效的。(The key point here is that reference widening depends on inheritance, in other words the IS-A test. Because of this, it's not legal to widen from one wrapper class to another, because the wrapper classes are peers to one another. For instance, it's NOT valid to say that Short IS-A Integer.)eg:Byte不能加宽到Short或Integer。

在一个方法匹配方案中吧加宽、装箱、var-arg结合的情况:

class Vararg {
          static void wide_vararg(long... x){
                System.out.println("long..."); 
          }
         static void box_vararg(Integer... x){
               System.out.println("Integer...");
         }
         public static void main(String [] args) {
             int i = 5;
             wide_vararg(5,5); // needs to widen and use var-args
             box_vararg(5,5); // needs to box and use var-args
         }
}
结果:
long...
Integer...
使用加宽、装箱、var-arg的重载方法的几条规则

  1. 基本加宽使用可能“最小的”方法参数。Primitive widening uses the "smallest" method argument possible.
  2. 不能从一种包装器类型加宽的另一种包装器类型.You CANNOT widen from one wrapper type to another. (IS-A fails.)
  3. 可以先装箱,后加宽(int可以通过Integer变成Object)You can box and then widen. (An int can become an Object, via Integer.)。
  4. 不能先加宽,后装箱(int不能变成Long)。You CANNOT widen and then box. (An int can't become a Long.)。原因:
  5. 可以结合使用装箱、var-arg、加宽。

分析以下代码的输出结果:package com.baidu;

public class Demo1 {

 
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  String[] strings = {"32","one","10.2","45"};
  float sum = 0;//改为 int sum = 0;
  for(String s : strings){
   try{
    sum += Float.parseFloat(s);//改为:sum += Integer.parseInt(s);
   }catch(NumberFormatException e){
    
    System.out.println(e.getMessage());
   }
  }System.out.println("sum="+sum);
 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值