您的位置:首页 > 其它

关于子类到父类强转的问题记录(学习整理)

2014-01-27 09:16 369 查看
//代码:
//父类
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中的定义了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: