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

//代码:		
//父类
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中的定义了。


  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值