我想知道在java中Dynamic Binding
的优点。动态绑定
public class Animal {
public String type = "mammal";
public void show() {
System.out.println("The animal is a: " + type);
}
}
public class Dog extends Animal {
public String type;
public Dog(String type){
this.type = type;
}
public void show() {
System.out.println("The dog is a: " + type);
}
}
public static void main(String[] args) {
Animal doggie = new Dog("daschund");
doggie.show(); // "The dog is a: daschund" (dynamic binding)
System.out.println("The type is: " + doggie.type); //"The type is: mammal" (static binding)
}
我想,这是一种继承策略。但有些人称之为动态绑定。这就是为什么,我假设它会有什么奇怪的。
相比什么优势? – Keppil
@Keppil:与“静态绑定”相比。 (请参阅OP的源代码中的最后一条评论。)继承的实例方法被覆盖,所以调用'doggie.show()'调用'Dog.show',它打印'Dog.type' - “动态绑定“ - 而字段不会被覆盖,所以'doggie.type'的使用使用'Animal.type' - ”静态绑定“。 – ruakh
@ruakh:啊,'静态绑定'部分是不可见的,我的坏。 – Keppil