java 父类引用指向子类对象---动态绑定之易错点详解

知识点:

1、java 中父类引用指向子类对象时动态绑定针对的只是子类重写的成员方法;

2、父类引用指向子类对象时,子类如果重写了父类的可重写方法(非private、非 final 方法),那么这个对象调用该方法时默认调用的时子类重写的方法,而不是父类的方法;

3、对于java当中的方法而言,除了final,static,private 修饰的方法和构造方法是前期绑定外,其他的方法全部为动态绑定;(编译看左边,运行看右边)


本质:java当中的向上转型或者说多态是借助于动态绑定实现的,所以理解了动态绑定,也就搞定了向上转型和多态。


实例演示:

package practice_19;

public class AlibabaMain01 {

	public static void main(String[] args) {

		
		System.out.println("--------父类引用指向子类对象-----------");
		
		Father instance = new Son();
		instance.printValue();
		instance.printValue2();
		System.out.println(instance.name);
		instance.printValue3();
		
		System.out.println("----------创建子类对象------------");
		
		Son son = new Son();
		son.printValue();
		son.printValue2();
		System.out.println(son.name);
		son.printValue3();
		
		System.out.println("---------创建父类对象-----------");
		
		Father father = new Father();
		father.printValue();
		father.printValue2();
		System.out.println(father.name);
		father.printValue3();
	}

}

class Father {

	public String name = "father";
	
	public void printValue() {
		System.out.println("this is father's printValue() method.---"+this.name);
	}
	
	public void printValue2(){
		System.out.println("this is father's printValue2() method.---"+this.name);
	}
	
	public static void  printValue3(){
		System.out.println("this is father's static printValue3() method.");
	}
}

class Son extends Father {

	public String name = "Son";

	public void printValue() {
		System.out.println("this is Son's printValue() method.---"+this.name);
	}
	
	public static void  printValue3(){
		System.out.println("this is Son's static printValue3() method.");
	}
}

运行结果:

--------父类引用指向子类对象-----------
this is Son's printValue() method.---Son
this is father's printValue2() method.---father
father
this is father's static printValue3() method.
----------创建子类对象------------
this is Son's printValue() method.---Son
this is father's printValue2() method.---father
Son
this is Son's static printValue3() method.
---------创建父类对象-----------
this is father's printValue() method.---father
this is father's printValue2() method.---father
father
this is father's static printValue3() method.

分析:

1、父类引用指向子类对象,对象调用的方法如果已经被子类重写过了则调用的是子类中重写的方法,而不是父类中的方法;

2、父类引用指向子类对象,如果想要调用子类中和父类同名的成员变量,则必须通过getter方法或者setter方法;

3、父类引用指向子类对象,如果想调用子类中和父类同名的静态方法,直接子类“类名点” 操作获取,不要通过对象获取;

4、父类引用指向子类对象的两种写法:(第二种得了解,面试中可能用到)

// 1、第一种常规写法
		Father instance = new Son();
		// 2、第二种变形写法;
		Son son = new Son();
		Father mson = (Father) son;



  • 10
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值