天天看點

多态及重寫案例示範

利用封裝,繼承,多态知識點彙集來解決Teatcher和Student不同行為的案例示範,代碼如下:

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("程式結束");

}

}