一张图解释---Java多态

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
posted @ 2015-07-30 18:13  小小鑫  阅读(319)  评论(0编辑  收藏  举报