java上轉型和下轉型(對象的多態性)


/*上轉型和下轉型(對象的多態性)
*上轉型:是子類對象由父類引用,格式:parent p=new son
*也就是說,想要上轉型的前提必須是有繼承關系的兩個類。
*在調用方法的時候,上轉型對象只能調用父類中有的方法,如果調用子類的方法則會報錯
*下轉型:是父類向下強制轉換到子類對象
*前提是該父類對象必須是經過上轉型的對象。
*
*代碼示例:*/

 1 abstract class Parent{
 2     abstract void grow();
 3 }
 4 class Son extends Parent{
 5     void grow(){
 6         System.out.println("我比父親成長條件好");
 7     }
 8     void dance(){
 9         System.out.println("我會踢球");
10     }
11 }
12 public class test {
13     public static void main(String[] args) {
14         //上轉型,用父類的引用子類的對象
15         Parent p=new Son();
16         //調用父類中有的方法
17         p.grow();
18         //p.dance();這里會報錯,因為父類中沒有dance()方法
19         
20         //對進行過上轉型的對象,進行強制下轉型
21         Son s=(Son)p;
22         //調用子類中的方法
23         s.dance();
24     }
25 }

 

/*
* 在我們寫程序中,很少會把代碼寫死,比如說還會有daughter類
* 然后在封裝函數來調用對象,說不定會用到子類的方法,這里我們來講解一下這一方面的知識*/

 1 abstract class Parent{
 2     abstract void grow();
 3 }
 4 class Son extends Parent{
 5     void grow(){
 6         System.out.println("我比父親成長條件好一點:son");
 7     }
 8     void play(){
 9         System.out.println("我會踢球");
10     }
11 }
12 class Daughter extends Parent{
13     void grow(){
14         System.out.println("我比父親成長條件好很多:daughter");
15     }
16     void dance(){
17         System.out.println("我會跳舞");
18     }
19 }
20 public class test {
21     public static void main(String[] args) {
22         Parent p=new Son();
23         show(p);
24         Parent p2=new Daughter();
25         show(p2);
26     }
27     public static void show(Parent p){
28             //現將父類中有的方法輸出
29             p.grow();
30             //對進行過上轉型的對象進行類型判斷,然后進行相應的強制下轉型
31             if(p instanceof Son){
32                 //判斷是哪個類的上轉型對象,然后進行下轉型
33                 Son s=(Son)p;
34                 //調用子類中的方法
35                 s.play();
36             }else if(p instanceof Daughter){
37                 Daughter d=(Daughter)p;
38                 d.dance();
39             }
40             
41     }
42 }

 

/*
* 在上轉型中,編譯程序的時候,看父類中有沒有對象調用的方法,沒有的話,就報錯
* 例如:Parent p=new Son();
* p.play();
* play()方法在父類中沒有,所以會報錯
* 在運行的時候,看子類中是否有調用的方法,有的話,運行子類的方法(重寫父類的方法)
*
* */


免責聲明!

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



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