JAVA语法:子类成员覆盖父类成员时的现象

1.重温JAVA语法:如父类Father与子类Son:

class Son extends Father{
	public String name = "son";
	
	public void say(){
		System.out.println("i am " + this.name);
	}
	
	public static void main(String[] args){
		Father f = new Father();
		System.out.println("Father f = new Father() : f.name => " + f.name);
		System.out.print("Father f = new Father() : f.say() => ");
		f.say();
		
		Father fa = new Son();
		System.out.println("Father fa = new Son() : fa.name => " + fa.name);
		System.out.print("Father fa = new Son() : fa.say() => ");
		fa.say();
		
		Son son = new Son();
		System.out.println("Son son = new Son() : son.name => " + son.name);
		System.out.print("Son son = new Son() : son.say() => ");
		son.say();
	}
}

输出结果为:

Father f = new Father() : f.name => father
Father f = new Father() : f.say() => i am father
Father fa = new Son() : fa.name => father
Father fa = new Son() : fa.say() => i am son
Son son = new Son() : son.name => son
Son son = new Son() : son.say() => i am son

由此可见,当子类与父类具有同样的成员属性(public)与方法(public)时,父类变量引用子类对象时,

a.父类变量调用成员属性时,子类成员属性不会覆盖父类成员属性,不具动态性;

b.父类变量调用方法时,子类方法将会覆盖父类方法,具有动态性。


为何会如此,目前不明白,还请知道的朋友赐教。大笑

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值