java的前期绑定和后期绑定使用示例
时间:2021-03-02 11:48:33|栏目:JAVA代码|点击: 次
后期绑定,是指在运行时根据对象的类型进行绑定,又叫动态绑定或运行时绑定。实现后期绑定,需要某种机制支持,以便在运行时能判断对象的类型,调用开销比前期绑定大。
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()
*/


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




