知识点:
1、java 中父类引用指向子类对象时动态绑定针对的只是子类重写的成员方法;
2、父类引用指向子类对象时,子类如果重写了父类的可重写方法(非private、非 final 方法),那么这个对象调用该方法时默认调用的时子类重写的方法,而不是父类的方法;
3、对于java当中的方法而言,除了final,static,private 修饰的方法和构造方法是前期绑定外,其他的方法全部为动态绑定;(编译看左边,运行看右边)
本质:java当中的向上转型或者说多态是借助于动态绑定实现的,所以理解了动态绑定,也就搞定了向上转型和多态。
package test; public class test{ public static void main(String[] args) { System.out.println("--------父类引用指向子类对象-----------"); Father instance = new Son(); instance.printValue(); //this is Son's printValue() method.---Son instance.printValue2(); //this is father's printValue2() method.---father System.out.println(instance.name); //father instance.printValue3(); //this is father's static printValue3() method. System.out.println("----------创建子类对象------------"); Son son = new Son(); son.printValue(); //this is Son's printValue() method.---Son son.printValue2(); //this is father's printValue2() method.---father System.out.println(son.name); //Son son.printValue3(); //this is Son's static printValue3() method. System.out.println("---------创建父类对象-----------"); Father father = new Father(); father.printValue(); //this is father's printValue() method.---father father.printValue2(); //this is father's printValue2() method.---father System.out.println(father.name); //father father.printValue3(); //this is father's static printValue3() method. } } class Father { public String name = "father"; public void printValue() { System.out.println("this is father's printValue() method.---"+this.name); } public void printValue2(){ System.out.println("this is father's printValue2() method.---"+this.name); } public static void printValue3(){ System.out.println("this is father's static printValue3() method."); } } class Son extends Father { public String name = "Son"; public void printValue() { System.out.println("this is Son's printValue() method.---"+this.name); } public static void printValue3(){ System.out.println("this is Son's static printValue3() method."); } }