码迷,mamicode.com
首页 > 其他好文 > 详细

父类不能转换成子类

时间:2016-09-14 16:33:31      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:

父类不能转换成子类

Exception in thread "main" java.lang.ClassCastException: Person cannot be cast to Boy
    at Test.main(Test.java:5)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

 

public class Test {

    public static void main(String[] args) {
        Person person = new Person();
        Boy boy = (Boy) person;
        boy.eat();
    }

}

class Person {
    public void eat() {
        System.out.println("The people were eating");
    }
}

class Boy extends Person {
    public void eat() {
        System.out.println("The boy were eating");
    }
}

 

父类不能转换成子类

标签:

原文地址:http://www.cnblogs.com/softidea/p/5872636.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!