原始檔案,創造一個Character的父類別,並在下方擁有兩個子類別:Magician、SwordsMan
創造兩個角色Mike跟Tim分別為兩個類別的物件實體測驗者
package tw.xxx.myselfpractice.polymorphism;
class Character{
private String name;
private int blood;
private int level;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getBlood() {
return blood;
}
public void setBlood(int blood) {
this.blood = blood;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
}
class Magician extends Character{
public void fight(){
System.out.println("Magician fight");
}
public void cure(){
System.out.println("MAGIC cure");
}
}
class SwordsMan extends Character{
public void fight(){
System.out.println("SwordsMan fight");
}
}
public class PolymorphismEx1 {
public static void main(String[] args) {
SwordsMan mike = new SwordsMan();
mike.setName("Mike");
mike.setBlood(100);
mike.setLevel(0);
System.out.println("Name="+mike.getName());
System.out.println("Blood="+mike.getBlood());
System.out.println("level="+mike.getLevel());
System.out.println("-------------");
Magician tim = new Magician();
tim.setName("Tim");
tim.setBlood(80);
tim.setLevel(0);
System.out.println("Name="+tim.getName());
System.out.println("Blood="+tim.getBlood());
System.out.println("level="+tim.getLevel());
System.out.println("-------------");
}
}
回傳結果---------------------------------------------------------------------
Name=Mike
Blood=100
level=0
-------------
Name=Tim
Blood=80
level=6
-------------
留言列表