当前位置: 代码迷 >> Java相关 >> 父类与子类,该怎么处理
  详细解决方案

父类与子类,该怎么处理

热度:9039   发布时间:2013-02-25 21:48:30.0
父类与子类
Java code
class Person{    String name;    int age;    public void say()    {        System.out.println("I am fater");    }    public void work()    {        System.out.println("I hava a job");    }}class Child extends Person{    public void say()    {        System.out.println("I am child");    }    public void dance()    {System.out.print("I can dance");}}


问题请见注解
Java code
    public static void main(String[] args) {        // TODO Auto-generated method stub        Person per=new Child();        per.say();        per.work();          Child ch=(Child)per;        ch.dance();        ch.say();        //为什么下面会报错呢?       Child ch1=(Child)new Person();    }


------解决方案--------------------------------------------------------

Child ch1=(Child)new Person()
父类的对象不能赋给子类的引用!
------解决方案--------------------------------------------------------
探讨
Child ch1=(Child)new Person()
父类的对象不能赋给子类的引用!
  相关解决方案