- 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()
父类的对象不能赋给子类的引用!
------解决方案--------------------