Java:子类调用超类方法的一种特殊情况

来源:互联网 发布:openframeworks知乎 编辑:程序博客网 时间:2024/04/30 02:45

在Java的子类中,可以通过super来明确调用超类(也即父类)的方法。但当所调用的超类的方法(1)中又调用了其它的方法(2)时,由于Java默认动态绑定,所以方法(2)调用的是子类中的方法。如下,示例(1)是一般的子类调用超类方法(即所调用的超类中的方法不再调用其它的需要动态绑定的方法),示例(2)是特殊的子类调用超类方法。

示例(1):

package MyTest;import java.util.*;public class MyTest {public static void main(String[] args) {B b = new B();System.out.println(b.test());}}class A {public String test() {return the_String;}private String the_String="A is OK!";}class B extends A{public String test() {return super.test();}private String the_String="B is YES!";}
说明:B类继承A类,并重写了方法test和重新定义了变量the_String,其中B类的test方法通过super调用父类A的test方法,,所以最终的输出结果是: A is OK! 。

示例(2):

package MyTest;import java.util.*;public class MyTest {public static void main(String[] args) {B b = new B();System.out.println(b.test());}}class A {public String test() {return the_String();}public String the_String() {return "A is OK!";}}class B extends A{public String test() {return super.test();}public String the_String() {return "B is YES!";}}
说明:B类继承A类,并重写了test和the_String方法,其中B类的test方法通过super调用父类A的test方法,A 的test方法又调用了the_String方法(默认动态绑定),所以最终的输出结果是: B is YES! 。




2 0