向上轉型與向下轉型(二)

 

向上轉型
向下轉型
定義
把對某個對象的引用視爲對其基類引用的做法
將超類的引用強制轉換爲子類類型
作用
調用導出類中的覆蓋方法

調用導出類中的擴展方法

 

代碼:

public class TestUpCastingOrDownCasting{

       public static void main(String[] args){

              father[] f = {new father(),new son1(),new son2(),new gs()};

             

              for(int i=0; i< f.length; i++){

                     System.out.println("==============" + f[i] + "==============");

                     if(f[i] instanceof son2){

                            son2 s2 = (son2)f[i];

                            s2.s();

                     }

                     f[i].f();

              }

       }

}

 

class father{

       public void f(){

              System.out.println("父類的方法!");

       }

}

 

class son1 extends father{

       public void f(){

              System.out.println("兒子1繼承父類的方法!");

       }

       public void s(){

              System.out.println("兒子1的方法!");

       }

}

 

class son2 extends father{

       public void f(){

              System.out.println("兒子2繼承父類的方法!");

       }

       public void s(){

              System.out.println("兒子2的方法!");

       }

}

 

class gs extends son2{

       public void f(){

              System.out.println("孫子通過兒子2繼承父類的方法!");

       }

       public void s(){

              System.out.println("孫子繼承兒子2的方法!");

       }

       public void gs(){

              System.out.println("孫子的方法!");

       }

}

輸出結果:
==========father@bdb503==========

父類的方法!

==========son1@b6e39f==========

兒子1繼承父類的方法!

==========son2@119dc16==========

兒子2的方法!

兒子2繼承父類的方法!

==========gs@c05d3b==========

孫子繼承兒子2的方法!

孫子通過兒子2繼承父類的方法!

執行語句:

==========father@bdb503==========

father f = new father();

f.f();

===對父類的操作

==========son1@b6e39f==========

father f = new son1();

f.f();

==向上轉型,覆蓋父類的方法

==========son2@119dc16==========

father f = new son2();

son2 s2 = (son2)f; ==向下轉型

s2.s();

f.f();  ==向上轉型

==========gs@c05d3b==========

father f = new son2();

son2 s2 = (son2)f;

s2.s();

f.f();

gs@c05d3b理解:

father f = new son2();

son2 s2 = (son2)f;

s2.s();

==執行語句過程中實現了一次向上轉型son2 s2 = (son2)f;和向下轉型s2.s();

f.f();

==實現的是向下轉型

     f[i] instanceof son2: 判斷instanceof左邊的對象是否是右邊的類的實例

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章