动态绑定的过程: a. 编译器查看对象的声明类型和方法名; b. 编译器查看调用方法时提供的参数类型。例如a.f(“hello”),编译器将会挑选f(String),而不是f(int),由于存在类型转换(int转换为double),所以可能会更复杂。如果编译器没找到参数类型匹配的方法,或者发现有多个方法与之匹配,就会报告一个错误。 c. 采用动态绑定调用方法的时候,一定调用与所引用对象的实际类型最合适的类的方法。如果a的实际类型是D,它是C类的子类,如果D定义了一个方法f(String),就直接调用它,否则将在D类的超类中寻找f(String),以此类推。
//父类
public class People {
public String name="人类";
public String getName(){
return this.name;
}
}
//子类
public class Student extends People{
public String name="学生";
public int age=15;
public String getName(){
return this.name;
}
public int getAge(){
return this.age;
}
}
//main方法
public class Test1 {
public static void main(String[] args) {
People people=new Student();
System.err.println("静态绑定结果");
System.out.println(people.name);
People a =new Student();
System.err.println("动态绑定结果");
System.out.println(a.getName());
}
}