利用封裝,繼承,多態知識點彙集來解決Teatcher和Student不同行爲的案例演示,代碼如下:
/**
* 人類
* @author Administrator
*
*/
public abstract class People {
private String name;
private int age;
public abstract void eat() ;
public void study() {
System.out.println("學習了..");
}
}
----------------------------------
public class Student extends People {
@Override
public void eat() {
// TODO Auto-generated method stub
System.out.println("正在喫雞");
}
public void study() {
System.out.println("正在學習大數據...");
}
/**
* 旅遊
*/
public void travel() {
System.out.println("去敘利亞一日遊...");
}
}
-------------------------------------------------
public class Teacher extends People {
@Override
public void eat() {
System.out.println("正在喫大龍呀");
}
public void study() {
System.out.println("正在學習人工智能...");
}
public void play() {
System.out.println("陪寶寶在玩耍");
}
}
----------------------------------------------
public class Test {
public static void main(String[] args) {
//父類引用 變量名=new 具體的子類();
//點看左 輸出看右
//創建一個數組 保存 2個人類的對象
People tt=new Teacher();
People ss=new Student();
People[] peoples=new People[2];
peoples[0]=ss;
peoples[1]=tt;
//循環來查看數組中2個對象的 屬性和方法
for (People people : peoples) {
people.eat();
//people.travel(); 學生所特有的
//需要再輸出 學生和老師的不同的方法
if ( people instanceof Student) {
Student student= (Student) people;
student.travel();
}
if (people instanceof Teacher) {
Teacher teacher=(Teacher) people;
teacher.play();
}
}
System.out.println("程序結束");
}
}