Java:子类调用超类方法的一种特殊情况
2014-05-05 10:02
357 查看
在Java的子类中,可以通过super来明确调用超类(也即父类)的方法。但当所调用的超类的方法(1)中又调用了其它的方法(2)时,由于Java默认动态绑定,所以方法(2)调用的是子类中的方法。如下,示例(1)是一般的子类调用超类方法(即所调用的超类中的方法不再调用其它的需要动态绑定的方法),示例(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! 。
相关文章推荐
- Java对象初始化步骤&&子类继承父类后变量与方法调用情况
- 父类的正常成员函数子类可以使用,并不是继承下来 的,子类是怎么调用父类的函数 : 可能是利用了一种叫函数名联编的方法.没有隐藏的情况下用函数名字来决定调用的函数.
- java第七周实验封装一类对象English,该类对象具有一种功能printEnglish输出英文字母表。再封装一类对象Greek,该类必须是English的子类,该类对象不仅可以调用方法printE
- java使用axis调用webservice时出现Connection reset by peer: socket write error的一种解决方法
- 一种实现 Java调用C++的DLL的方法
- JAVA基础 -从父类的引用如何调用子类中独有的方法
- 亲身体会:一种需要取得子类详细信息的情况(五种方法)
- java this 子类调父类,父类再调用子类已覆盖的方法及属性(又一次理解)
- Java 父类构造函数中调用子类重写的方法
- 关于Java中子类调用父类方法
- java创建一个子类对象是会调用父类的构造方法会不会创建父类
- Java中子类调用父类构造方法的问题分析
- Java 中父类怎么调用子类的方法?
- JAVA C# 区别:用父类变量调用子类的方法
- Java继承,子类实例化时,调用父类的无参构造方法
- java子类如何调用父类变量和方法
- java程序练习:尝试创建一个父类,在父类中创建两个方法,在子类中覆盖第二个方法,为子类创建一个对象,将他向上转型到基类并调用这个方法。
- Java子类,父类方法调用时序
- java创建一个子类对象是会调用父类的构造方法会不会创建父类
- java中子类,父类的方法调用及属性值