java 多态 向上造型

最近在读java 编程思想,在读多态一章时,遇到了一个问题,在此记录一下。

 1 package main.demo;
 2 
 3 class Super{
 4     public int filed =0;
 5 
 6     public int getFiled() {
 7         return filed;
 8     }
 9 }
10 
11 class Sub extends Super{
12     public int filed = 1;
13 
14     @Override
15     public int getFiled() {
16         return filed;
17     }
18 
19     public int getSuperFiled(){
20         return super.getFiled();
21     }
22 }
23 
24 
25 public class Demo1 {
26     public static void main(String[] args) {
27         Super sup = new Sub();
28         System.out.println(sup.filed+"   "+ sup.getFiled());
29 
30         Sub sub = new Sub();
31         System.out.println(sub.filed+"  "+sub.getFiled()+"  "+sub.getSuperFiled());
32     }
33 
34 
35 }

执行结果:

          

分析:

 Super sup = new Sub();   首先声明了一个变量sup,类型是 Super,然后创建了一个Sub类型的对象,赋值给sup变量,也就是说,除了函数被覆盖了之外,其他的都无变化。所以说,成员变量编译
和运行都看左边。但是函数被复写了,所以说,对于非静态成员函数编译看左边,运行看右边。对于静态函数编译和运行都要看左边。静态函数先于对象被加载,所以没有被复写。
posted @ 2018-09-25 16:20  天晴、、、  阅读(393)  评论(0编辑  收藏  举报