public class B {

public static void go(Long n) {
System.out.println("Long");
}

public static void go(Short n) {
System.out.println("Short");
}

public static void go(int n) {
System.out.println("int");
}

public static void main(String[] args) {
short y = -20;
long z = 7;
go(y);
go(z);
}
}
怎么不同的JDK, 这段代码有能编译过的,有能编译不过的呢? 结果也不一样。

解决方案 »

  1.   

    JDK1.5以上,才提供了自动封装,也就是long 到Long之间的转换,能够自己识别。
      

  2.   

    1.5的新特性,楼主可以找本core java,书的最后几页有对JDK5.0的介绍
      

  3.   

    对的,在JDK1.4以下的版本(包括1.4) long Long 这些基本数据类型 必须包装成对象 才行,在JDK1.5开始增加自动box 和unbox,就是说,对于基本数字类型来说,他会自动进行包装和解包装。
      

  4.   

    因为long跟Long之间能转换, 所以结果是 int , Long ?
      

  5.   

    请问在哪能下载core java 这本书呢? 没找到中文版本的。
      

  6.   

    short y = -20; 
    这是 JDK1.5以后的自动封装特性
    JDK1.5之前的版本需要
    如2楼那样
      

  7.   

    public class B {

    public static void go(Long n) {
    System.out.println("Long");
    }

    public static void go(Short n) {
    System.out.println("Short");
    }

    public static void go(int n) {
    System.out.println("int");
    }

    public static void main(String[] args) {
    short y = -20;
    long z = 7;
    int w = 6;
    short q = (short) -20;
    go(y);
    go(z);
    go(w);
    go(q);
    }
    }
    重新修改后, 为什么都跑int呢?  结果是
    int
    Long
    int
    int