在Java中,多态分为运行时多态和编译时多态。
(1)编译时多态:在编译时可以确定调用哪个方法,例如方法的重载、重写中的一种情况即:子类 对象=new 子类()或者父类 对象 =new 父类
(2)运行时多态:在程序运行时才能确定调用哪个方法,例如方法的重写 :父类 对象=new 子类(),实际创建的是子类对象,后面方法也是调用子类的方法。
示例:
public class Father {
public Father(){
System.out.println("Father");
}
public void Sport(){
System.out.println("Sport");
}
}
public class Son extends Father{
public void Walk(){
System.out.println("Walk");
}
public void Sport()
{
System.out.println("Son Sport");
}
public Son(){
System.out.println("Son");
}
public static void main(String[] args) {
Father f=new Son();
f.Sport();
System.out.println(f.getClass());
}
}
运行结果: