Java中的后期绑定 [英] Late Binding in Java

查看:169
本文介绍了Java中的后期绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了所有关于堆栈溢出时后期绑定的类似问题,对于将这个问题标记为重复的人,我将完全不同意.首先,我在另一个问题上找到了这个示例,但是我不明白如何知道何时在编译时确定什么东西以及何时在运行时确定什么东西.基本上,我的问题的症结可以归结为两点:

I have searched through all the similar questions on late binding on stack overflow, and I would severely disagree with anyone who marks this question as a duplicate. First off, i found this example on another question, but I do not understand how I am supposed to know when something is decided during compile time and when something is decided during run time. Basically, the crux of my question boils down to two things:

  • 在此示例中,必须使我得出一个逻辑结论:一种方法是后期绑定,另一种方法是早期绑定

  • What in this example must bring me to the logical conclusion that one method is late binding and another is early binding

我怎么知道在Java的运行时或编译期间何时决定执行哪种方法的决定?

How do I know when the decision about which version of a method to execute is decided during run-time or compile time in Java

代码:

class A
{
    public void foo()
    {
        System.out.println("Class A");
    }
}

class B extends A
{
    public void foo()
    {
        System.out.println("Class B");
    }
}

public class C
{
    public static void main(String [] args)
    {
        A a=new A();
        B b=new B();
        A ref=null;

        /* 
            early binding  --- calls method foo() of class A and
            decided at compile time
        */ 
         a.foo(); 

        /* early binding --- calls method foo() of class B and
            decided at compile time
        */
          b.foo(); 

        /* late  binding --- --- calls method foo() of class B and
           decided at Run time
     */ 
        ref=b;
        ref.foo(); }
}

推荐答案

在所有方面都是错误的.在每种情况下,运行时都会根据对象的运行时类型确定要调用的方法.在编译时唯一的决定是调用final,private或static方法,或者在一组重载方法中进行选择(如果重载方法不是final,private或static,这仍可能导致运行时选择.)

Wrong on all counts. The method to be called is decided at runtime, in every case here, based on the runtime type of the object. The only decisions made at compile time are for calls to final, private, or static methods, or choices among a set of overloaded methods (which could still lead to runtime choices if the overloaded methods are not final, private, or static.)

这篇关于Java中的后期绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆