Java动态绑定条件

时间:2018-10-18 02:29:53

标签: java

我的教授提供了有关何时在Java中进行动态绑定的一些信息,但是在阅读了堆栈溢出和其他网站上的许多文章后,我不确定是否能获得正确的信息。我的教授在演讲中指出,在以下情况下需要动态绑定:

1)声明一个变量为其类型为超类,并且

2)变量类型及其子类之间可能有不止一种可能的多态方法

我不确定条件1),因为到处读取的状态都表明,只要存在方法重写,就需要动态绑定。 一个例子:

public class Polygon{
    public void getPerimeter(){
        System.out.println("Polygon method")
    }
}

public class Rectangle() extends Polygon{
    public void getPerimeter(){
        System.out.println("Rectangle method")

    }
}


public static void main(String[] args){
    Rectangle a = new Rectangle();
    a.getPerimeter();
}

此代码是否需要动态绑定?矩形不是超类,因此不满足条件1)。但是,Rectangle中的方法将覆盖超类Polygon中的方法。编译器如何知道要运行哪种方法?

1 个答案:

答案 0 :(得分:0)

在Java中,政治形态由两个方面组成:

  • 类型继承:使用超类型类型的引用指向子类型类型的实例(例如:Polygon p = new Rectangle())。
  • 动态绑定:在运行时根据对象的实际类型将方法签名绑定到方法实现(例如:对于p.getPerimeter()getParamater方法是最特定于实际调用类型p的。)

由于在您的示例中,在定义Rectangle时没有使用超类类型,因此没有在使用polimorphism。

如果要使用策略化,请按以下方式重构代码:

public static void main(String[] args){
    // using a supertype reference
    Polygon a = new Rectangle();
    /** 
        there are two methods available here, the one inherited from Polygon and 
        the one Rectangle overrides. Dynamic binding ensures the right method gets 
        picked up at runtime, based on the actual type of the Polygon object 
        (which in this case in Rectange)
    */
    a.getPerimeter();
}

您可能会争辩说即使在示例中也发生了动态绑定(因为在运行时获取了正确的实现),但是以这种方式使用动态绑定会破坏动态绑定的目的(因为如果您将引用定义为与实际对象,您将始终只能得到一个且只有一个实现)。

您的教授可能是指多态性,而不是动态绑定