java - 由于对象是子类,程序如何决定运行哪个方法
问题描述
所以我有以下代码:
import java.util.Scanner;
class Shape{
double length, breadth;
Shape(double l, double b) { //Constructor to initialize a Shape object
length = l;
breadth = b;
}
Shape(double len) { //Constructor to initialize another Shape object
length = breadth = len;
}
double calculate(){ // To calculate the area of a shape object
return length * breadth ;
}
}
public class Test1 extends Shape {
double height;
Test1(double l, double h) {
super(l);
height = h;
}
Test1(double l, double b, double h) {
super(l, b);
height = h;
}
@Override
double calculate(){
return length*breadth*height;
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
double l=sc.nextDouble();
double b=sc.nextDouble();
double h=sc.nextDouble();
Test1 myshape1 = new Test1(l,h);
Test1 myshape2 = new Test1(l,b,h);
double volume1;
double volume2;
volume1 = myshape1.calculate();
volume2 = myshape2.calculate();
System.out.println(volume1);
System.out.println(volume2);
}
}
而且我不明白它如何决定calculate()
运行哪个方法,因为它们都是从子类对象调用的,但其中一个决定运行父类方法。
它与构造函数重载有关吗?如果是怎么办?
解决方案
构造函数重载与“运行哪个方法”无关。构造函数仅用于初始化实例,而“运行哪个方法”可能是与方法重载有关的问题,而您的问题并非如此。
在这两种情况下:
volume1 = myshape1.calculate();
volume2 = myshape2.calculate();
... ->类层次结构calculate()
中的最低可用实现被调用 - 也就是说,在您的情况下。Test1
java.lang.Object
Test1::calculate
您不调用超类calculate()
,而是您的类calculate()
使用从超类继承的字段Shape
,如下所示:
double calculate(){
return length*breadth*height;
}
当您实例化类时,它是使用其超类的所有成员(甚至是私有的)创建的,这就是您使用超类字段的原因,就好像它们是在相关类中定义的一样。
旁注:private
超类的成员在子类中不可直接访问。您需要适当的访问器/获取器来访问它们。
推荐阅读
- amazon-web-services - LoadBalancer 和 Autoscaling 组:当 AZ 不可用时会发生什么?
- awk - Gawk 匹配一个单词 - 一个意外匹配
- scrapy - 为什么运行特定的蜘蛛不起作用(但运行所有的蜘蛛)
- html - 使导航栏居中
- python - MultiGPU Kmeans 聚类与 RAPID 冻结
- python - 使用 GLM http_status = 412 进行训练时出现“H2OResponseError:ModelBuilderErrorV3”“缺少训练帧”
- delphi - 如何将指向句柄列表的指针传递给 UpdateProcThreadAttribute 函数
- android - 导航组件:跳转到动态根目录并清除后台堆栈
- jquery - 响应在 jquery ajax 响应中总是为空
- node.js - Node Js 文件替换实用程序