首先来看一段代码:
class="java">public class ExtendDemo { public static void main (String[] args) { SuperClass superClass = new SuperClass(); SuperClass subClass = new SubClass(); superClass.find();//根据对象引用类型决定调用父类或子类的方法 subClass.find(); //根据对象引用类型决定调用父类或子类的方法 System.out.println("+++++++++++++++++++++++++++++++++"); superClass.test(); subClass.test(); System.out.println("+++++++++++++++++++++++++++++++++"); SubClass subClass1 = new SubClass(); superClass.find();//根据对象引用类型决定调用父类或子类的方法 subClass1.find(); //根据对象引用类型决定调用父类或子类的方法 } } class SuperClass { public static void find () { System.out.println("find"); } public void test () { System.out.println("superclass test method"); } } class SubClass extends SuperClass { public static void find () { System.out.println("hello"); } @Override public void test () { System.out.println("subclass test method"); } }
?? 运行结果:
??
find find +++++++++++++++++++++++++++++++++ superclass test method subclass test method +++++++++++++++++++++++++++++++++ find hello
??? 由上面的结果可以看出:静态方法没有被重载;上面的例子总子类中有相同声明的静态方法, 具体调用父类中的方法还是子类中的方法是根据对象引用的类型来决定,如果对象引用类型是父类,就调用父类中的find()方法,如果对象引用是子类,就调用子类的静态方法;这与重载的概念不相符,重载的概念是根据对象实际类型来调用具体的方法
??
?? 上面main方法的java的字节码:
?
new com/malone/pattern/SuperClass dup invokespecial com/malone/pattern/SuperClass/<init>()V astore_1 new com/malone/pattern/SubClass dup invokespecial com/malone/pattern/SubClass/<init>()V astore_2 aload_1 pop invokestatic com/malone/pattern/SuperClass/find()V //调用父类的find方法,invokestatic 指令调用静态方法,根据对象引用类型判断调用方法 aload_2 pop invokestatic com/malone/pattern/SuperClass/find()V //调用父类的find方法,invokestatic 指令调用静态方法,根据对象引用类型判断调用方法 getstatic java/lang/System/out Ljava/io/PrintStream; ldc "+++++++++++++++++++++++++++++++++" invokevirtual java/io/PrintStream/println(Ljava/lang/String;)V aload_1 invokevirtual com/malone/pattern/SuperClass/test()V aload_2 invokevirtual com/malone/pattern/SuperClass/test()V getstatic java/lang/System/out Ljava/io/PrintStream; ldc "+++++++++++++++++++++++++++++++++" invokevirtual java/io/PrintStream/println(Ljava/lang/String;)V new com/malone/pattern/SubClass dup invokespecial com/malone/pattern/SubClass/<init>()V astore_3 aload_1 pop invokestatic com/malone/pattern/SuperClass/find()V //调用父类的find方法,invokestatic 指令调用静态方法,根据对象引用类型判断调用方法 aload_3 pop invokestatic com/malone/pattern/SubClass/find()V //调用子类的find方法,invokestatic 指令调用静态方法,根据对象引用类型判断调用方法 return
??? invokevirtual 指令调用实例方法,调用实例方法的时候才会根据对象的实际类型来调用具体的方法,才能实现重写
?
??
?