关于子类到父类强转的问题记录(学习整理)
2014-01-27 09:16
417 查看
//代码: //父类 public class Father { protected String name="父亲属性"; public void method() { System.out.println("父类方法,对象类型:" + this.getClass()); } } //子类 public class Son extends Father { protected String name="儿子属性"; public void method() { System.out.println("子类方法,对象类型:" + this.getClass()); } public static void main(String[] args) { Father sample = new Son(); System.out.println("调用成员: " + sample.name); System.out.print("调用方法: "); sample.method(); } }
程序运行结果:
调用成员: 父亲属性
调用方法: 子类方法,对象类型:class NO1.Son
原因:
Java语言规范中有:
If the class declares a field with a certain name, then the declaration of that field is said to hide any and all accessible declarations of fields with the same name in superclasses, and superinterfaces of the class.
......
A hidden field can be accessed by using a qualified name (if it is static) or by using a field access expression (§15.11) that contains the keyword super or a cast to a superclass type. See §15.11.2 for discussion and an example.
“如果一个类声明了一个成员变量,则此声明会隐藏其父类和父接口中所有同名的、可以访问的成员变量。
...
被隐藏的成员变量如果是static的,则可以使用全名来访问它(这里全名就是package.class.field的形式),如果是非static的,可以用super.field 或强制类型转换为父类后进行访问。“
顾名思义,hide是把父类的成员变量隐藏起来,你不会一眼就看见它(不能用正常的、简单的方式访问到它),而要揭开一层盖子才能发现(用super或cast到父类)。而override相信是比较清楚的,覆盖后原来的方法已经不存在了,你是无论如何也看不见它的。
回到Father和Son
Father sample = new Son();
相当于
Father sample = new Father();
Son s = new Son();
sample = s;
不准确
相当于Father sample = (Father)(new Son());更准确。
因此sample.name相当于有一个Cast的动作,因此就访问到了被hide了的Father的name。而sample.method();虽然也有Cast但是method已经被override了,也就只可能调用Son中的定义了。
相关文章推荐
- 关于父类子类转换的小记录
- WCF-005:关于 WCF 基础连接已经关闭 连接被意外关闭-不是使用父类指向子类问题
- [cocos2d-x]关于update回调,以及继承后子类调用父类的Update处理的问题
- Java中关于子类覆盖父类的抛出异常问题
- 关于子类调用父类构造方法的问题
- 关于子类和父类加载时一些问题
- 关于子类与父类的转换, 还有多态的说明 - 回复 "靳承柱" 和 "志成" 的问题
- VGScene 学习日志一:关于TvgScene设置为透明后,里面的按钮不能点击的问题记录
- Java编程关于子类重写父类方法问题的理解
- 关于父类和子类的初始化问题
- 关于C++中子类调用父类方法的一个问题
- 有关于递归函数的一些学习记录(Recursion)走楼梯,递归找出最两个数的大公约数,汉诺塔问题
- [C++] 关于子类声明与父类同名同类型的成员变量的问题
- 关于PHP中构造函数以及子类继承父类构造函数的相关问题
- 关于继承与构造函数重载的问题(初始化子类构造函数中的父类对象)求解答。。。
- 【java学习笔记】关于继承中父类和子类中语句的执行循序
- stm32f407 学习过程中时钟问题(整理记录)
- Java学习之子类与父类实例化问题~
- 关于子类和父类具有相同属性的问题
- java 中关于子类调用父类构造函数问题