请解释Java中静态和动态绑定的概念。
我所掌握的是Java中的静态绑定发生在编译时,而动态绑定发生在运行时,静态绑定使用类型(Java中的类)信息进行绑定,而动态绑定使用对象来解析绑定。
这是我理解的代码。
public class StaticBindingTest {
public static void main (String args[]) {
Collection c = new HashSet ();
StaticBindingTest et = new StaticBindingTest();
et.sort (c);
}
//overloaded method takes Collection argument
public Collection sort(Collection c) {
System.out.println ("Inside Collection sort method");
return c;
}
//another overloaded method which takes HashSet argument which is sub class
public Collection sort (HashSet hs){
System.out.println ("Inside HashSet sort method");
return hs;
}
}
并且上述程序的输出在集合排序方法中
对于动态绑定...
public class DynamicBindingTest {
public static void main(String args[]) {
Vehicle vehicle = new Car(); //here Type is vehicle but object will be Car
vehicle.start(); //Car's start called because start() is overridden method
}
}
class Vehicle {
public void start() {
System.out.println("Inside start method of Vehicle");
}
}
class Car extends Vehicle {
@Override
public void start() {
System.out.println ("Inside start method of Car");
}
}
输出在 Car 的 start 方法中。请指教:这种理解是否正确,请指教更多例子。谢谢。