java 上溯造型與下塑造型


父類:

package com.neusoft.chapter07;

public class Father {
    
    public int i = 1;
    public void say(){
        System.out.println("我是杜江");
    }
}

子類:

package com.neusoft.chapter07;

public class Son extends Father{
    public int i = 2;
    public void say(){
        System.out.println("我是嗯哼");
    }
}

1、父類指向父類:

package com.neusoft.chapter07;

public class Test {
    public static void main(String[] args) {
               Father f = new Father();
               System.out.println(f.i);
               f.say();
    }
}

 結果:

  1

  我是杜江

-----------------------------------------------------------------------------

2、子類指向子類:

package com.neusoft.chapter07;

public class Test {
    public static void main(String[] args) {
               Son s = new Son();
               System.out.println(s.i);
               s.say();
    }
}

 結果:

  2

  我是嗯哼

------------------------------------------------------------------------------

3、父類指向子類-----(上溯造型)

package com.neusoft.chapter07;

public class Test {
    public static void main(String[] args) {
               Father f = new Son();
               System.out.println(f.i);
               f.say();
    }
}

結果:

  1

  我是嗯哼

-----------------------------------------------------------------------------

4、父類轉子類-----(下塑造型)

package com.neusoft.chapter07;

public class Test {
    public static void main(String[] args) {
               Father f = new Son();
               Son s = (Son)f;
               System.out.println(s.i);
               s.say();
    }
}

結果:

  2

  我是嗯哼

上溯造型特征:

  具有繼承或實現關系

  父類和子類均有一個成員變量i最后拿到的是父類的i

  父類和子類均有一個say方法,最后執行的是子類的方法(say方法重寫)

下塑造型:

  先上轉再向下轉


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM