多态的条件:
1)继承
2)重写父类的方法
3)父类的引用指向子类的对象
Class Father{
private String name;
private int age;
public void say(){
system.out.println("hello,i'm father");
}
public void money(){
system.out.println("make money");
}
}
Class son extends Father{
private String name;
private int age;
public void say(){
system.out.println("hello,i'm son");
}
public void goSchool(){
system.out.println("go to school");
}
}
Class Test{
Father father = new Son();//向上转型
father.say();//输出i'm son
father.money();
father = (Son) father ;//向下转型
father.goSchool();
}
简而言之分为两种情况:
子类继承父类时取决于子类是否覆盖父类方法.如果子类覆盖父类方法,则执行子类方法;
如果没有覆盖,则执行父类方法.如果想要调用子类的没有被覆盖的方法,此时就需要向下转型 然后才能调用子类未覆盖父类的方法。