多态性是面向对象编程的基础。它允许多个方法使用同一个接口。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();
}
}