静态绑定: 在程序执行前方法已经被绑定,此时由编译器或其它连接程序实现。例如:C。针对java简单的可以理解为程序编译期的绑定;这里特别说明一点,java当中的方法只有final,static,private和构造方法是前期绑定
动态绑定: 在运行时根据具体对象的类型进行绑定。 动态绑定的典型发生在父类和子类的转换声明之下 比如:Parent p = new Children();
总结: 声明的是父类的引用,但是执行过程中调用的是子类的对象,程序先寻找子类对象的method方法,但是没有找到,于是向上转型去父类寻找。 但是子类的对象调用的是父类的成员变量。 所以必须明确,运行时绑定,针对的只是对象的方法。 如果试图调用子类的成员变量name,该怎么做? 最简单的就是将该成员变量封装成方法getter形式 example1:
package test; public class Father { public void method(){ System.out.println("父类方法,对象类型:"+this.getClass()+"."); } } package test; /** * 声明的是父类的引用,但是执行过程中调用的是子类的对象, * 程序先寻找子类对象的method方法,但是没有找到, * 于是向上转型去父类寻找 * @author Administrator * */ public class Son extends Father{ public static void main(String[] args) { Father sample=new Son();//向上转型 sample.method(); } }输出: 父类方法,对象类型:class test.Son.
example2:
package test; public class Father { public void method(){ System.out.println("父类方法,对象类型:"+this.getClass()+"."); } } package test; /** * 由于子类重写了父类的method方法,所以会调用子类的method方法 * 执行,因为子类对象有method方法而没有向上转型去寻找 * * @author Administrator * */ public class Son1 extends Father{ public void method(){ System.out.println("子类方法,对象类型:"+this.getClass()); } public static void main(String[] args) { Father sample=new Son1(); sample.method(); } }输出: 子类方法,对象类型:class test.Son1
example3:
package test1; public class Father { protected String name="父亲属性"; public void method(){ System.out.println("父类方法,对象类型:"+this.getClass()); } } package test1; /** * 这个结果表明,子类的对象调用的是父类的成员变量。 * 所以必须明确,运行时绑定,针对的只是对象的方法。 * 如果试图调用子类的成员变量name,该怎么做? * 最简单的就是将该成员变量封装成方法getter形式 * @author Administrator * */ public class Son extends Father{ protected String name="儿子属性"; public void method(){ System.out.println("子类方法,对象类型:"+this.getClass()); } public static void main(String[] args) { Father sample=new Son(); System.out.println("调用的成员:"+sample.name); sample.method(); } }输出: 调用的成员:父亲属性 子类方法,对象类型:class test1.Son
example4:
package test2; public class Father { protected String name="父亲属性"; public String getName(){ return name; } public void method(){ System.out.println("父类方法,对象类型:"+this.getClass()); } } package test2; /** * 如果试图调用子类的成员变量name,该怎么做? * 将该成员变量封装成方法getter形式 * @author Administrator * */ public class Son extends Father{ protected String name="儿子属性"; public String getName(){ return name; } public void method(){ System.out.println("子类方法,对象类型:"+this.getClass()); } public static void main(String[] args) { Father sample=new Son();//向上转型 System.out.println("调用的成员:"+sample.getName()); } }输出: 调用的成员:儿子属性