超类引用指向子类对象能否访问子类成员?示例调用疑问解析
问题解答
问题1:我们能否使用持有子类对象的超类引用变量访问子类的成员?
不能直接访问子类独有的成员(即超类中未定义的方法或属性)。但如果子类重写了超类已有的方法,超类引用调用该方法时,会执行子类的重写版本——这是Java多态特性的核心表现。
问题2:为何示例程序中,超类引用能调用到子类的multiplication方法?
你混淆了编译期检查和运行时执行的逻辑:
- 编译阶段:编译器仅检查超类
Calculation是否存在multiplication(int, int)方法,发现超类本身就定义了这个方法,因此编译通过,不会报错。 - 运行阶段:Java的动态绑定机制会根据实际对象的类型(
My_Calculation),执行子类重写后的multiplication方法,所以最终输出子类的打印内容。
示例程序输出
The sum of the given numbers:30
The difference between the given numbers:10
The product of the given numbers in sub class is:200
示例程序代码
class Calculation { int z; public void addition(int x, int y) { z = x + y; System.out.println("The sum of the given numbers:" + z); } public void Subtraction(int x, int y) { z = x - y; System.out.println("The difference between the given numbers:" + z); } public void multiplication(int x, int y) { z = x * y; System.out.println("The product of the given numbers in super class is :" + z); } } public class My_Calculation extends Calculation { public void multiplication(int x, int y) { z = x * y; System.out.println("The product of the given numbers in sub class is:" + z); } public static void main(String args[]) { int a = 20, b = 10; Calculation demo = new My_Calculation(); demo.addition(a, b); demo.Subtraction(a, b); demo.multiplication(a, b); } }
内容的提问来源于stack exchange,提问作者Sonu Gupta
相关产品推荐
相关产品推荐

