多態性是面向對象編程的基礎。它允許多個方法使用同一個接口。Java從多個方面支持多態性,最爲突出的是:每個方法都可以被子類重寫;設立interface關鍵字。當把子類對象當作父類對象來看時,就只能調用父類中原有定義的屬性和方法。子類自己擴展的屬性和方法就不能調用了。當把子類對象當作父類對象來看時,如果子類重寫了父類中的方法,則調用該方法時調用的是子類重寫後的方法。
package JAVA_Project_01_05;
import java.util.Date;
class Student {
String name;
Date date= new Date();
int hour=date.getHours();
public void goToSchol(Student student) {
Student stu = new Student();
if (this.hour<=7&&this.hour>5){
this.clockMe(stu);
}else{
System.out.println("洗臉刷牙");
}
}
public void clockMe(Student stu) {
System.out.println("叮鈴鈴...叮鈴鈴..." + this.name + "起牀了");
}
}
class Pupil extends Student {
public void goToSchool(Student student) {
System.out.println("我是小學生");
Pupil pupil = new Pupil();
if (hour<= 6 && hour>5){
this.clockMe(pupil);
}else{
System.out.println("要鍛鍊身體!!!");
}
}
public void clockMe(Student stu) {
System.out.println("小鳥咕咕叫..." + this.name + "起牀了");
}
public void showInfo() {
System.out.println("我是小學生!");
}
}
class Undergraduate extends Student {
public void goToSchool(Student stu) {
System.out.println("我是大學生");
Undergraduate graduate = new Undergraduate();
if (hour<=9&&hour>5){
this.clockMe(graduate);
}else{
System.out.println("繼續睡覺!!!");
}
}
public void clockMe(Student me) {
System.out.println("小鼓咚咚咚..." + this.name + "起牀了");
}
public void showInfo() {
System.out.println("我是大學生!");
}
}
public class TextPolymiorphism {
public static void main(String[] args) {
System.out.println("1.當時間在5-7點時");
Student student = new Pupil();
student.name = "Susan";
student.goToSchol(student);
student = new Undergraduate();
student.name = "Tom";
student.goToSchol(student);
Pupil pupil = new Pupil();
pupil.goToSchool(pupil);
pupil.showInfo();
}
}