edit2
对不起,没关系,我刚刚添加了
public double cylinderSurfaceArea() {
return 2 * base.circleArea() + base.circleCirumference() * 2 * height;
}
}
没有错误代码。这是正确的吗?
编辑:
感谢所有回答的人。从那以后,我将以前的 Cylinder 类更改为阅读。现在我想更进一步,添加
public double cylinderSurfaceArea() {
return 2 * Math.PI * radius * radius + 2 * Math.PI * radius * h;
}
但是它现在说半径(甚至 r)返回错误“找不到符号 - 可变半径”。不应该从 Circle 类中找到/声明符号吗?
我想做的是使用单独的 Circle.java
类计算圆柱体的体积。
例如,到目前为止,我的 circle.java 有以下内容
public class Circle {
public double radius;
public Circle(double r) {
radius = r;
}
public double circleArea() {
return Math.PI * radius * radius;
}
public double circleCirumference() {
return Math.PI * 2 * radius;
}
}
问题从这里开始。在制作 Cylinder
类时,我从以下几点开始:
public class Cylinder extends Circle {
如果是这样,总的来说我有:
public class Cylinder extends Circle {
public Circle base;
public double height;
public Cylinder(double r, double h) {
height = h;
base = new Circle(r);
}
public double getVolume() {
return base.circleArea * height;
}
}
但是,我在以下之后一直收到错误:
public Cylinder(double r, double h) {
说明:
constructor
Circle
in classCircle
cannot be applied to given types;required:double
; found:noarguments
; reason:actual and formal arguments lists differ in length."
有人能把我推向正确的方向吗?我做错了什么?
最佳答案
发生这种情况是因为构造函数的第一次调用是隐式的 super()
引自Java Tutorials :
If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error.
您需要在 Circle
类中创建一个无参数构造函数,或者像这样更改您的 Cylinder
构造函数:
public Cylinder(double r, double h) {
super(r);
height = h;
}
关于java - 如何使用 circle.java 计算圆柱体的 getVolume。 [2个类(class)],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19568974/