package sonandfather;
class father{
void eat(){
System.out.println("father eat");
}
void hitson(){
System.out.println("father hit son");
}
}
class sonXiaoming extends father{
void eat(){
System.out.println("sonXiaoming eat");
}
void play(){
System.out.println("sonXiaoming play");
}
}
class sonXiaogang extends father{
void eat(){
System.out.println("sonXiaogang eat");
}
void sing(){
System.out.println("sonXiaogang sing");
}
}
public class SonextendsFather {
public static void main(String args[]) {
father f=new sonXiaoming(); //父类类型引用子类对象,向上转型。
f.eat(); //调用的是子类的方法,规则是先从子类找该方法,找不到先父类找
f.hitson();//子类无该方法,向父类找
// f.play(); 报错,父类f无该方法
father f1=new father();
f1.eat(); //父类对象调用父类方法
f1.hitson();
sonXiaoming xm=new sonXiaoming();
xm.eat();
xm.play();
father fa=new sonXiaoming();
method(fa);
method(new father());
method(new sonXiaoming());
method(new sonXiaogang());
}
public static void method(father f) {
if(f instanceof sonXiaoming){
sonXiaoming xm=(sonXiaoming)f; //向下转型
xm.play();
}
if(f instanceof sonXiaogang){
sonXiaogang xg=(sonXiaogang)f; //向下转型
xg.sing();
}
}
}
控制台输出:
sonXiaoming eat
father hit son
father eat
father hit son
sonXiaoming eat
sonXiaoming play
sonXiaoming play
sonXiaoming play
sonXiaogang sing
多态在代码中的体现: 父类或者接口的引用指向其子类的对象。 多态的条件: 1.有联系继承、实现。 2.方法必须覆盖。