2012年5月31日 星期四

Java Basic(55)-Introduction to Polymorphism


public class food {
void eat(){
System.out.println("this food is great");
}
}



public class potpie extends food{
void eat(){
System.out.println("this potpie is great");
}
}

public class tuna extends food{
void eat(){
System.out.println("this tuna is great");
}
}



class apples{
public static void main(String[] args){
food bucky[]=new food[2]; 陣列
bucky[0]=new potpie(); 這裡的新對象
bucky[1]=new tuna(); 這裡的新對象
for(int x=0;x<2;++x){
bucky[x].eat();
}
}
}

由於potpietuna extendsfood,你不需要為tuna.tunaObject(類似的東西
這是運行時的結果: 

this potpie is great
this tuna is great



沒有留言:

張貼留言