您的位置:首页 > 编程语言 > Java开发

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

2014-05-05 10:02 357 查看
在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! 。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐