標籤:
1.向上轉型:編譯器自動進行,不需要聲明
Snowboard s = new Snowboard ();Object o = s; (相當於指向Snowboard的內部Object執行個體,所有類都繼承於Object類)
①當o試圖引用 Snowboard專屬的方法時,是不會成功的
②當o引用被子類override過method時,調用的是該子類的method
2. 向下轉型:強制類型轉換,需要聲明
① 先指向裡面,可以隨時向下轉型指向外面
Object o = new Snowboard();
Snowboard s = (Snowboard) o ;
② 現在轉型的父類引用必須是指向了子類對象,否則向下轉型不成功
Object o = new object ();
Snowboard s = (Snowboard) o; //這樣的向下轉型是不成功的,因為已經o引用是指向Object類的執行個體的,並沒有被子類繼承。
3. 多態的三個用法:
1.參考型別可以是實際物件類型的父類
Animal [] animals = new Animal [5];
animals [0] = new Dog();
animals [1] = new Cat();
animals [2] = new Wolf();
animals [3] = new Hippo();
animals [4] = new Lion();
2. 參數可以多態
class Ver {
public void giveShot(Animal a){
a.makeNoise();
}
}
class PetOwner {
public voi start(){
Vet v = new Vet();
Dog d = new Dog();
Hippo h = new Hippo();
v.giveShot(d);
v.giveShot(h);
}
}
3. 傳回值多態:《第一行代碼》P375
public class MyService extends Service {
private DownloadBinder mBinder = new DownloadBinder();
class DownloadBinder extends Binder {
public void startDownload() {
Log.d("MyService", "startDownload executed");
}
public int getProgress() {
Log.d("MyService", "getProgress executed");
return 0;
}
}
@Override //當活動與Service成功綁定時,會回調這個方法
public IBinder onBind(Intent intent) {
return mBinder; // binder extends Object implements IBinder, 繼承關係:IBinder > Binder > DownloadBinder
}
}
===================================================================================
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) { //Service返回的mbinder(實際是指向Ibinder)
downloadBinder = (MyService.DownloadBinder) service; //所以向下轉型成downloadBinder。
downloadBinder.startDownload();
downloadBinder.getProgress();
}
};
4. 參考資料:
①http://www.cnblogs.com/mengdd/archive/2012/12/25/2832288.html②Headfirst Java
一張圖解釋---Java多態