为什么这是静态结合而不是动态结合



我仍然对静态和动态之间的差异有些困惑。据我所知,动态使用静态使用类型时使用对象,并且在编译时间内静态时,在运行时解决了该动态。因此

key.compareto(list [position-1])使用动态绑定

public static void insertionSort (Comparable[] list)
{
    for (int index = 1; index < list.length; index++)
    {
        Comparable key = list[index];
        int position = index;
        while (position > 0 && key.compareTo(list[position-1]) < 0) // using dynamic binding
        {
            list[position] = list[position-1];
            position--;
        }
            list[position] = key;
    }
}

为什么(this.lastname.compareto(s1.lastname))使用静态绑定?

private String firstName;
private String lastName;
private int totalSales;
@Override
public int compareTo(Object o) {
    SalePerson s1 = (SalePerson)o;
    if (this.totalSales > s1.getTotalSales())
    {
        return 1;
    }
    else if (this.totalSales < s1.getTotalSales())
    {
        return -1;
    }
    else //if they are equal
    {
        return (this.lastName.compareTo(s1.lastName)); //why is this static binding??
    }
}

您的问题还不完整,也不包括所有相关代码。但是,这是不同绑定之间的基本差异

Java具有静态和动态结合。绑定是指变量绑定到特定数据类型时。

静态/早期结合在编译时间进行:私人,最终和静态方法和变量。以及用于超载方法

在运行时进行动态/晚绑定,用于以下方式:可以是过度方法的方法。这就是在运行时启用多态行为的原因。

要进一步证明这一点,请查看此代码,看看您是否可以确定何时和晚期的绑定:

/* What is the output of the following program? */
public class EarlyLateBinding {
public boolean equals(EarlyLateBinding other) {
    System.out.println("Inside of overloaded Test.equals");
    return false;
}
public static void main(String[] args) {
    Object t1 = new EarlyLateBinding(); //1
    Object t2 = new EarlyLateBinding(); //2
    EarlyLateBinding t3 = new EarlyLateBinding(); //3
    Object o1 = new Object();

    Thread.currentThread().getStackTrace();
    int count = 0;
    System.out.println(count++); 
    t1.equals(t2);//n
    System.out.println(count++);
    t1.equals(t3);//n
    System.out.println(count++); 
    t3.equals(o1);
    System.out.println(count++); 
    t3.equals(t3);
    System.out.println(count++);
    t3.equals(t2);
}
}

答案:

  • 是在计数之后,因此返回的结果为0之前。因此,从0开始,并按照您的期望进行。
  • 唯一等于早期凸起对象方法的情况实际上是调用的是语句3。
  • 这是因为等价方法被超载(注意:不同的与对象类等于)
  • 相比
  • 因此,早期凸线类型与变量T3绑定编译时间。

在此代码中

public static void insertionSort (Comparable[] list)
{
    for (int index = 1; index < list.length; index++)
    {
        Comparable key = list[index];
        int position = index;
        while (position > 0 && key.compareTo(list[position-1]) < 0) 
        {
            list[position] = list[position-1];
            position--;
        }
            list[position] = key;
    }
}

可以是实现可比接口的任何东西参考。

但是在此代码中,

@Override
public int compareTo(Object o) {
    SalePerson s1 = (SalePerson)o;
    if (this.totalSales > s1.getTotalSales())
    {
        return 1;
    }
    else if (this.totalSales < s1.getTotalSales())
    {
        return -1;
    }
    else //if they are equal
    {
        return (this.lastName.compareTo(s1.lastName));
    }
}

编译器知道 S1 的类型,因此它使用静态绑定

最新更新