从Javarevisited博客文章:
这是静态绑定和动态绑定之间的一些重要区别:
- Java中的静态绑定发生在编译时,而动态绑定发生在运行时。
private,final以及static方法和变量使用静态结合和由编译器所键合而虚拟方法基于运行时对象在运行期间接合。- 静态绑定使用
Type(class在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;> }> }输出 :内部集合排序方法
Java动态绑定示例
> 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");> }> }输出: 汽车内部启动方式



