Java特性之多态父类与子类之间的调用

问题描述:

  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异常。

posted @ 2016-12-05 10:19  冰西瓜先生  阅读(4715)  评论(0编辑  收藏  举报