天天看點

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

向上轉型

向下轉型

定義

把對某個對象的引用視為對其基類引用的做法

将超類的引用強制轉換為子類類型

作用

調用導出類中的覆寫方法

調用導出類中的擴充方法

代碼:

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{

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

       public void s(){

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

class son2 extends father{

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

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

class gs extends son2{

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

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

       public void gs(){

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

輸出結果:

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

父類的方法!

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

兒子1繼承父類的方法!

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

兒子2的方法!

兒子2繼承父類的方法!

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

孫子繼承兒子2的方法!

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

執行語句:

father f = new father();

f.f();

===對父類的操作

father f = new son1();

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

father f = new son2();

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

s2.s();

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

son2 s2 = (son2)f;

對gs@c05d3b了解:

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

==實作的是向下轉型

     f[i] instanceof son2: 判斷instanceof左邊的對象是否是右邊的類的執行個體