前期绑定与后期绑定的一点理解

前期绑定是指在程序编译的时候就确定了某一个类里面方法的调用,在运行的时候会解析到被执行代码的绝对地址。例如有一个基类Base,有一个子类Child继承/派生于基类,如果定义一个基类类型的子类对象,再调用此对象的方法,方法输出为父类方法里的内容。

后期绑定是在程序运行的时候才会确定代码的地址。也就是说定义一个基类类型的子类对象,再调用此对象的方法,方法输出为子类方法里的内容。

C++中可以利用virtual关键字来实现,java中除了变量、final、static为前期绑定,其他可方便的实现后期绑定。下面分别为C++和java的相关实现代码:

#include "stdafx.h"
#include "iostream"
using namespace std;

class Base{
public:
	char *name = "Base";//前期绑定
	void testMethod(){<span style="white-space:pre">	</span>//前期绑定
		cout << "Base Field" << endl;
	}
	virtual void testMethodTwo(){}//用virtual定义虚函数,可实现后期绑定。
};
class Child : public Base{
public:
	char *name = "Child";
	void testMethod(){
		cout << "Child Field" << endl;
	}
	void OutName(){
		cout << name << endl;
	}
	void testMethodTwo(){
		cout << "ChildFieldTwo" << endl;
	}
};
int _tmain(int argc, _TCHAR* argv[])
{
	Base* temp = new Child();
	temp->testMethod();
	//temp->OutName();//基类中不存在,编译错误
	temp->testMethodTwo();
	while (1);
	return 0;
}
输出结果为:Base Field

ChildFieldTwo

以下为java代码:

/*
 * Early Binding:Binding while Compiling.
 * Late Binding: Binding while running. According to the type of Object.
 */
class Base{
	public String name = "base"; //变量和static final都属于前期绑定。
	public static void BaseField(){
		System.out.println("Static Base");
	}
	public void ChildField() {//普通函数属于后期绑定。
		System.out.println("Not Static Base");
	}
}
public class TestBinding extends Base{
	public String name = "Child";
	public static void BaseField(){
		System.out.println("Static Child");
	}
	public void ChildField(){
		System.out.println("Not Static Child");
	}
	
	public static void testString(Base base){
		System.out.println(base.name);
	}
	public static void testBaseField(Base base){
		base.BaseField();
	}
	public static void testChildField(Base base){
		base.ChildField();
	}
	public static void main(String[] args) {
		TestBinding t = new TestBinding();
		testString(t);
		testBaseField(t);
		testChildField(t);
	}
}
输出为:

base
Static Base
Not Static Child


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值