問題描述:
Java三大特性,封裝、繼承、多態,一直沒搞懂其中多態是什么,最近研究了一下,關於父類和子類之間的調用。下面是一個測試類,源代碼如下:
1 package com.test; 2 3 public class BaseClass { 4 5 /** 6 * @param args 7 */ 8 public static void main(String[] args) { 9 // TODO Auto-generated method stub 10 Father f = new Father(); 11 f.sayHi(); 12 Son s = new Son(); 13 s.sayHi(); 14 s.sayHello(); 15 Father fs = new Son(); 16 fs.sayHi(); 17 //Son sf = (Son) new Father(); 18 //sf.aa(); 19 //sf.sayHi(); 20 System.out.println("---------------------------"); 21 System.out.println(f.getHeight()); 22 System.out.println(s.getHeight()); 23 System.out.println(fs.getHeight()); 24 System.out.println(fs.getClass()); 25 } 26 27 } 28 29 class Father { 30 31 public int height; 32 Father(){ 33 height = 5; 34 } 35 Father(int height){ 36 this.height= height; 37 } 38 39 public void sayHi(){ 40 System.out.println("Hi,World!I'm Father."); 41 } 42 43 public void aa(){ 44 System.out.println("Hi,aa!I'm Father."); 45 } 46 47 public int getHeight(){ 48 return height; 49 } 50 } 51 52 class Son extends Father { 53 54 public void sayHello(){ 55 System.out.println("Hello,World!I'm Son."); 56 } 57 58 @Override 59 public void sayHi(){ 60 System.out.println("Hi,World!I'm Son."); 61 } 62 }
輸出結果:
1 Hi,World!I'm Father. 2 Hi,World!I'm Son. 3 Hello,World!I'm Son. 4 Hi,World!I'm Son. 5 --------------------------- 6 5 7 5 8 5 9 class com.test.Son
總結:
1.父類引用指向父類對象,子類引用指向子類對象,就是正常的類生成。
2.父類引用指向子類對象時,父類引用可以調用父類里定義的方法,比如sayHi();但是不能調用父類沒用,子類有的方法,比如sayHello();會報The method sayHello() is undefined for the type Father錯誤。但是,父類引用指向子類對象時,調用的方法是子類的,也就是控制台輸出的“Hi,World!I'm Son.”調用.getClass(),會打印"class com.test.Son"。
3.由於Son繼承Father,所以所有的.getHeight();都是輸出5.
4.子類對象指向父類引用的,需要強制轉換成子類,見代碼的注釋地方,既可以調用父類方法,也可以調用子類方法,但是會報com.test.Father cannot be cast to com.test.Son異常。