复制代码
1
2
3
4public abstract class Animal { abstract void eat(); }
复制代码
1
2
3
4
5
6
7
8
9
10
11public class Cat extends Animal { @Override void eat() { System.out.println("吃鱼"); } void catchMouse() { System.out.println("抓老鼠"); } }
复制代码
1
2
3
4
5
6
7
8
9
10
11public class Dog extends Animal { @Override void eat() { System.out.println("吃骨头"); } void watchHouse() { System.out.println("看家"); } }
类转换异常ClaaCastExcaption
这段代码可以通过编译,但是运行时,却报出了 ClassCastException ,类型转换异常!
这是因为,明明创建了 Cat类型对象,运行时,当然不能转换成Dog对象的。这两个类型并没有任何继承关系,不符合类型转换的定义。
具体报错信息:
Exception in thread “main” java.lang.ClassCastException: cn.itcast.day10.Test04.Cat cannot be cast to cn.itcast.day10.Test04.Dog
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15public class Test { public static void main(String[] args) { Animal a=new Cat(); a.eat(); //正确向下转型 Cat cat=(Cat)a; cat.catchMouse(); //错误向下转型 Dog dog=(Dog)a;//编译不报错,运行报错。类转换异常ClaaCastExcaption dog.watchHouse(); } }
为了避免ClassCastException的发生,Java提供了 instanceof 关键字,给引用变量做类型的校验,格式如下
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17public class Test { public static void main(String[] args) { Animal a = new Cat(); a.eat(); //变量名 intanceOf 数据类型 //这个变量本来是不是这个类型 if (a instanceof Cat) { Cat cat = (Cat) a; cat.catchMouse(); } else if(a instanceof Dog){ Dog dog = (Dog) a; dog.watchHouse(); } } }
最后
以上就是激昂金毛最近收集整理的关于基础第一阶段day10——ClassCastException类型转换异常的全部内容,更多相关基础第一阶段day10——ClassCastException类型转换异常内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复