我对静态和动态之间的区别仍然有点困惑。据我所知,动态使用对象而静态使用类型,动态在运行时解析,而静态则在编译期间。所以不应该这个.lastName.compareTo(s1.lastName)使用动态绑定吗?
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??
}
}
答案 0 :(得分:1)
您的问题不完整,并未包含所有相关代码。然而,这是不同绑定之间的基本区别
Java具有静态和动态绑定。绑定是指变量绑定到特定数据类型时。
静态/早期绑定在编译时完成:private,final和static方法和变量。还有重载方法
动态/后期绑定在运行时完成:可以覆盖方法的方法。这就是在运行时启用多态行为的原因。
要进一步证明这一点,请查看此代码,看看您是否可以确定何时进行早期和晚期绑定:
/* 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);
}
}
答案:
答案 1 :(得分:1)
在此代码中
@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));
}
}
key 可以是实现 Comparable 接口的任何东西,因此在编译时编译器不知道确切的类型,因此在运行时通过使用解析类型键引用的对象。
但是在这段代码中,
{{1}}
编译器知道 s1 的类型,因此它使用静态绑定