后期绑定,是指在运行时根据对象的类型进行绑定,又叫动态绑定或运行时绑定。实现后期绑定,需要某种机制支持,以便在运行时能判断对象的类型,调用开销比前期绑定大。
java中的static方法和final方法属于前期绑定,子类无法重写final方法,成员变量(包括静态及非静态)也属于前期绑定。除了static方法和final方法(private属于final方法)之外的其他方法属于后期绑定,运行时能判断对象的类型进行绑定。验证程序如下:
class base
{
//成员变量,子类也有同样的成员变量名
public string test="base field";
//静态方法,子类也有同样签名的静态方法
public static void staticmethod()
{
system.out.println("base staticmethod()");
}
//子类将对此方法进行覆盖
public void notstaticmethod()
{
system.out.println("base notstaticmethod()");
}
}
public class derive extends base
{
public string test="derive field";
public static void staticmethod()
{
system.out.println("derive staticmethod()");
}
@override
public void notstaticmethod()
{
system.out.println("derive notstaticmethod()");
}
//输出成员变量的值,验证其为前期绑定。
public static void testfieldbind(base base)
{
system.out.println(base.test);
}
//静态方法,验证其为前期绑定。
public static void teststaticmethodbind(base base)
{
//the static method test() from the type base should be accessed in a static way
//使用base.test()更加合理,这里为了更为直观的展示前期绑定才使用这种表示。
base.staticmethod();
}
//调用非静态方法,验证其为后期绑定。
public static void testnotstaticmethodbind(base base)
{
base.notstaticmethod();
}
public static void main(string[] args)
{
derive d=new derive();
testfieldbind(d);
teststaticmethodbind(d);
testnotstaticmethodbind(d);
}
}
/*程序输出:
base field
base staticmethod()
derive notstaticmethod()
*/
如对本文有疑问,
点击进行留言回复!!
相关文章:
-
-
-
-
-
java实现通讯录管理系统
本文实例为大家分享了java实现通讯录管理系统的具体代码,供大家参考,具体内容如下完成项目的流程:1.根据需求,确定大体方向 2.功能模块分析 3.界面实现 4...
[阅读全文]
-
-
-
-
Java中生产者消费者问题总结
生产者-消费者算是并发编程中常见的问题。依靠缓冲区我们可以实现生产者与消费者之间的解耦。生产者只管往缓冲区里面放东西,消费者只管往缓冲区里面拿东西。这样我们避免...
[阅读全文]
-
-
网友评论