Java多態–構造方法的內部方法多態
package com.pgy.base;
/**
* 構造器內部的多態方法的行爲
* 構造方法調用內部的方法時,會執行所創建對象的內部方法
* @author admin
* @version $Id: PolymorphismDemo.java, v 0.1 2015年9月1日 上午8:30:31 admin Exp $
*/
class Person {
void run() {
System.out.println("Person run");
}
Person() {
System.out.println("Person run before student");
run();//當子類繼承父類的構造方法的時候,此處調用的run,是創建對象student的run方法,而不是父類的run方法,因爲父類對象沒有被創建
System.out.println("Person run after student");
}
}
class Student extends Person {
private int age = 1;
//當父類調用此方法的時候,age沒有被初始化,內存分配給age初始化的二進制0
void run() {
System.out.println("Student run method, age = " + age);
}
Student(int age) {
System.out.println("Student run construct,age = " + age);
}
}
public class PolymorphismDemo {
public static void main(String[] args) {
new Student(10);
}
}
/*console*/
//Person run before student
//Student run method, age = 0
//Person run after student
//Student run construct,age = 10