package Demo;
/**
*測試向上造型
*所謂的向上造型就是 父類的引用(棧中)指向子類的對象(堆中)
* 打個比喻:
* 人是父類,學生是子類。 人能夠吃飯,說話; 學生能夠吃飯(重寫),學習;(學生吃飯方法是獨特的)
* 當學生向上造型為人時,我們再調用吃飯這個方法時,我們調用的其實是學生特有的吃飯方法;
* 下面的例子大家可以好好想想,分別運用到,繼承,方法重寫,構造方法初始化成員變量,向上造型(多態的運用)
* @author Administrator
*
*/
public class demo5 {public static void main(String[] args) {
People model = new People();
model.age = 20;
model.sex = "男";
model.test();//People:男 20
People model2 = new Student();
model2.test();//Student:100 2
}
}
class People{
int age;
String sex;
public void test(){
System.out.println(“People:”+this.sex+” “+this.age);
}
}
class Student extends People{
String score;
String grade;
public Student() {}
Student(String score,String grade){
this.score = score;
this.grade = grade;
}
public void test(){
Student student = new Student("100","2");
System.out.println("Student:"+student.score+" "+student.grade);
}
}