一張圖解釋---Java多態

來源:互聯網
上載者:User

標籤:

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多態

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.