标签:
Java面向对象作业-用接口方式测试向下转型
根据视频的里实例 我们直接修改Test2测试方法:
1 package com.java1234.chap03.sec13; 2 3 public class Test2 { 4 5 public static void main(String[] args) { 6 People p1=new Student(); 7 p1.say(); 8 9 Student student=(Student) p1; 10 student.say(); 11 12 Teacher teacher=(Teacher) p1; 13 teacher.say(); 14 } 15 }
运行报错:
我是学生
我是学生
Exception in thread "main" java.lang.ClassCastException: com.java1234.chap03.sec13.Student cannot be cast to com.java1234.chap03.sec13.Teacher
at com.java1234.chap03.sec13.Test2.main(Test2.java:12)
类型转换异常 向下转型是不安全的,必须知道具体实现类;
标签:
原文地址:http://www.cnblogs.com/eaglezb/p/5961805.html