首页 > 编程语言 > 详细

java 多态 向上造型

时间:2018-09-25 16:30:34      阅读:152      评论:0      收藏:0      [点我收藏+]

最近在读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变量,也就是说,除了函数被覆盖了之外,其他的都无变化。所以说,成员变量编译
和运行都看左边。但是函数被复写了,所以说,对于非静态成员函数编译看左边,运行看右边。对于静态函数编译和运行都要看左边。静态函数先于对象被加载,所以没有被复写。

java 多态 向上造型

原文:https://www.cnblogs.com/muqingzhi123/p/9700151.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!