java 多态 向上造型
2024-08-28 06:12:08
最近在读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变量,也就是说,除了函数被覆盖了之外,其他的都无变化。所以说,成员变量编译
和运行都看左边。但是函数被复写了,所以说,对于非静态成员函数编译看左边,运行看右边。对于静态函数编译和运行都要看左边。静态函数先于对象被加载,所以没有被复写。
最新文章
- 【转】windows环境下安装win8.1+Mac OS X 10.10双系统教程
- Mysql导入导出非常慢解决办法
- iptables的扩展匹配
- js关闭当前页面(窗口)的几种方式总结(转)
- 不错的 iOS 开发辅助工具
- DOM优化
- GDC2016【全境封锁(Tom Clancy's The Division)】对为何对应Eye Tracked System,以及各种优点的演讲报告
- A Tour of Go Advanced Exercise: Complex cube roots
- WIN7 如何关闭Aero
- android学习日记03--常用控件tabSpec/tabHost
- A题进行时--浙大PAT 1001-1010
- SVG-1
- 树莓派高级GPIO库,wiringpi2 for python使用笔记(四)实战DHT11解码
- ie浏览器css中的行为expression详解
- SSH免密码(日志三)
- springBoot整合多数据源
- openstack Q版部署-----keystone认证服务安装配置(3)
- dispatch_block_t
- 9.22 下午 (document对象)
- C语言:字符串输出流输出文件中的数据。