静态绑定与动态绑定
静态绑定/前期绑定:简单的可以理解为程序编译期的绑定。java当中的方法只有final,static,private和构造方法是前期绑定
- private方法不能被继承,只能通过这个类自身的对象来调用,因此private方法和类绑定在了一起。
- final方法可以被继承,但不能被重写(覆盖), 将方法声明为final类型,一是为了防止方法被覆盖,二是为了有效地关闭java中的动态绑定。
- static方法可以被子类继承,但是不能被子类重写(覆盖),可以被子类隐藏。
动态绑定/后期绑定:在运行时根据具体对象的类型进行绑定。动态绑定的过程:虚拟机提取对象的实际类型的方法表 -> 虚拟机搜索方法签名 -> 调用方法。
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
import java.util.ArrayList;import java.util.List;public class { public static void main(String[] args) { List<Animal> list = new ArrayList<>(); Animal dog = new Dog(); System.out.println("dog instance of Animal dog: " + dog.getClass()); Animal cat = new Cat(); System.out.println("cat instance of Animal cat: " + cat.getClass()); // list.add(cat); list.add(dog); for (Animal animal : list) { if (animal.name == "animal") System.out.println("animal.name = animal, so instance fields are statically bound"); if (animal.toString().contains("color") || animal.toString().contains("eyes")) System.out.println("invoke subclass method, so instance methods are dynamically bound"); System.out.println(animal.toString()); } Animal.staticMethod(); // static methods can be inherited Cat.staticMethod(); // static method can be hidden but not override Dog.staticMethod(); // it's deprecated, but it works and invoke the partent class static method Animal dog2 = new Dog(); dog2.staticMethod(); }}class Animal { static String staticVar = "Animal StaticVar"; String name = "animal"; public Animal() { System.out.println("Animal is created"); } public String toString() { return name; } // @Override cause compile error public static void staticMethod() { System.out.println("I am Animal static method"); }}class Dog extends Animal { static String staticVar = "Dog StaticVar"; String name = "dog"; String color = "color"; public String toString() { return super.toString() + ":" + color; } public static void staticMethod() { System.out.println("I am Dog static method"); }}class Cat extends Animal { static String staticVar = "Cat StaticVar"; String name = "cat"; String eyes = "eyes"; public String toString() { return super.toString() + ":" + eyes; }}
参考资料: