本文共 1085 字,大约阅读时间需要 3 分钟。
目标类A:
public class A { static { System.out.println("A=====static"); } { System.out.println("A====代码块"); } public void get(int a , long b) { System.out.println(a+"====="+b); }}
目标类B继承A:
public class B extends A { static { System.out.println("B+++++static"); } { System.out.println("B++++代码块"); } @Override public void get(int a, long b) { // TODO Auto-generated method stub super.get(a, b); } public void get(long b , long a) { System.out.println(a+"@@@@@@"+b); } public void get(long b , int a) { System.out.println(a+"+++++++++++"+b); } public void get(int a, int b) { System.out.println(a+">>>>>>>>>>>"+b); }}
测试类:
public class ExtendsTest { @Test public void test() { B b= new B(); b.get(2, 5); }}
public class ExtendsTest { @Test public void test() { B b= new B(); b.get(2, 5L);//5修改为了long型 }}
运行结果:
A=====staticB+++++staticA====代码块B++++代码块2>>>>>>>>>>>5
A=====staticB+++++staticA====代码块B++++代码块2=====5
从上面的运行结果可以看出来:程序运行首先会执行父类A的静态代码块,其次运行子类B的静态代码块,在到父类的代码块、子类的代码块,最后才是函数的调用;当有多个重名函数时,在决定要调用哪一个函数的过程中,首先是按照参数类型来匹配的,也就是说寻找所有重载版本中最匹配的,然后才看变量的动态类型,进行动态绑定。
转载地址:http://jwegf.baihongyu.com/