如果没有,那么对于下面的程序,如何访问子类的乘法(方法)因为我使用了超类Calculation的引用变量,它保存了子类My_Calculation的对象。 以下程序的输出是: 给定数字的总和:30 给定数字之间的差异:10 子类中给定数字的乘积是: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);
}
}
我期待错误,因为我们只能使用超类的引用来访问超类的成员。
在java中子类与其父类有相同的方法称为方法覆盖。 当通过超类引用调用重写方法时,Java 确定要执行该方法的哪个版本(超类/子类)。调用哪个方法取决于所引用对象的类型,而不是引用变量的类型。 这就是 Java 中的运行时多态性。
在您的代码中,调用了子类的 multiplication 方法,因为对象的真实类型是 My_Calculation