classA{}classBextendsA{}@Testpublicvoidtest4()throws Exception {
A a =newA();try{
B b =(B) a;}catch(ClassCastException e){
System.out.println(e.getMessage());}
B b =newB();
A aa = b;// cn.hengyumo.review.r1.Test1$A cannot be cast to cn.hengyumo.review.r1.Test1$B}
实现同一个接口的父子类同样无法直接转型
interfaceI{}classDimplementsI{}classEextendsDimplementsI{}@Testpublicvoidtest5()throws Exception {
D d =newD();try{
E e =(E) d;}catch(ClassCastException e){
System.out.println(e.getMessage());}
I i = d;try{
E e =(E) i;}catch(ClassCastException e){
System.out.println(e.getMessage());}// cn.hengyumo.review.r1.Test1$D cannot be cast to cn.hengyumo.review.r1.Test1$E// cn.hengyumo.review.r1.Test1$D cannot be cast to cn.hengyumo.review.r1.Test1$E}
包装类之间可以任意转换,但是基础类型转高精度类型的包装类时无法再进行隐式转换
@Testpublicvoidtest6()throws Exception {int a =2;
Integer i = a;int aa = i;// cannot cast 'int' to 'java.lang.Long'// Long l = (Long) a;
Long l =(long) a;long ll = l;// cannot cast 'int' to 'java.lang.Short'// Short s = (Short) a;
Short s =(short) a;short ss = s;// Long lll = s;// cannot cast 'java.lang.Short' to 'java.lang.Long'// Long lll = (Long) s;}
包装类为null时转换基本类型会抛出空指针异常
@Testpublicvoidtest7()throws Exception {
Boolean b = null;try{boolean bb = b;}catch(NullPointerException e){
System.out.println(e.getMessage());}
Integer i = null;try{long l = i;}catch(NullPointerException e){
System.out.println(e.getMessage());}// null// null}