动态绑定:可以使多态更加灵活。
向上转型:父类对象的引用指向子类对象。隐式转换。Father f = new Son();
向下转型:子类对象的引用指向父类对象。需显式转换。Father f = new Son(); Son s = (Son) f;
动态绑定:当虚拟机调用一个实例方法时,他会基于对象实际的类型来选择所调用的方法。是多态的一种。具体表现在向上转型中。因为只有在运行时才知道具体运行的是哪个实例。(在运行时绑定)
public class Father{ public void say(){ System.out.println("This is Father"); } public static void main(String[] args){ Father f = new Son(); f.say(); } } class Son extends Father{ public void say(){ System.out.println("This is Son"); } }
输出:
静态绑定: 在编译时绑定, 只有private、static、final是静态绑定的
public class Father{ public void say1(){ System.out.println("This is Father 1"); } public void say2(){ System.out.println("This is Father 2"); } public static void main(String[] args){ Father f = new Son(); System.out.println("这是动态绑定 f.say1()"); f.say1(); System.out.println("这是静态绑定 f.say2()"); f.say2(); } } class Son extends Father{ public void say1(){ System.out.println("This is Son 1"); } public static void say2() { System.out.println("This is Son 2"); } }
输出: