【发布时间】:2012-04-28 04:03:02
【问题描述】:
请解释一下Java中静态绑定和动态绑定的概念。
我所掌握的是Java中的静态绑定发生在编译时,而动态绑定发生在运行时,静态绑定使用Type(Java中的类)信息进行绑定,而动态绑定使用Object来解析绑定。
这是我理解的代码。
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 方法中。请指教:这种理解是否正确,请指教更多例子。谢谢。
【问题讨论】:
-
这似乎是现在的常态……
标签: java