1.向上轉型:編譯器自動進行,不須要聲明html
Snowboard s = new Snowboard (); Object o = s; (至關於指向Snowboard的內部Object實例,全部類都繼承於Object類)
①當o試圖引用 Snowboard獨有的方法時,是不會成功的
②當o引用被子類override過method時,調用的是該子類的method
2. 向下轉型:強制類型轉換,須要聲明ide
① 先指向裏面,能夠隨時向下轉型指向外面
Object o = new Snowboard();
Snowboard s = (Snowboard) o ;
② 如今轉型的父類引用必須是指向了子類對象,不然向下轉型不成功
Object o = new object ();
Snowboard s = (Snowboard) o; //這樣的向下轉型是不成功的,由於已經o引用是指向Object類的實例的,並無被子類繼承。
3. 多態的三個用法:spa
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. 參考資料:code
①http://www.cnblogs.com/mengdd/archive/2012/12/25/2832288.html ②Headfirst Java