【发布时间】:2021-04-25 21:37:51
【问题描述】:
public class Main {
public static void main(String[] args) {
shape[] myShapes = new shape[3];
myShapes[0] = new cube(3);
myShapes[1] = new Sphere(2);
myShapes[2] = new Cylinder(3, 4);
for (shape: myShapes)
System.out.println()
}
}
class cube extends shape {
public double side;
public double newSide;
public double volume;
public double surface;
public cube(double side) {
this.side = side;
}
public void cubeVolume(){
volume = Math.pow(side,3);
System.out.println (volume);
}
public void cubeSurface(){
surface = Math.pow(side,2) * 6;
System.out.println (surface);
}
}
abstract class shape{
protected double volume;
protected double surface;
}
public class Sphere extends shape {
public double radius;
public double volume;
public double area;
public double i = 4;
public double j = 3;
public Sphere(double radius) {
this.radius = radius;
}
public void sphereVolume(){
volume = i/j * Math.PI * Math.pow(radius,3);
System.out.println(volume);
}
public void surfaceArea(){
area = 4 * Math.PI * Math.pow(radius,2);
System.out.println(area);
}
}
public class Cylinder extends shape{
public double radius;
public double height;
public double cylinderVolume;
public double cylinderArea;
public Cylinder(double radius, double height) {
this.radius = radius;
this.height = height;
}
public void surface(){
cylinderArea = 2 * Math.PI * radius * height;
System.out.println(cylinderArea);
}
public void volume(){
cylinderVolume = Math.PI * Math.pow(radius, 2) * height;
System.out.println(cylinderVolume);
}
}
我不认为标题很好地包含了我的问题。我正在实例化一个新对象并将该对象存储在数组 myShapes 中。每个对象的类都有一个计算表面积和体积的方法。我需要调用所有这些方法,我相信这可以通过 for 循环来完成,但我不确定如何。我完全被难住了。
【问题讨论】:
-
这将有助于我们查看您的类层次结构。什么是 Cube、Sphere、Cylinder 和 Shape 对象?如果在 Shape 对象中声明了表面积和体积方法,那么它应该可以工作。
-
您的基类
shape是否声明了您要调用的那些方法? -
对不起,我刚刚添加了其他类。形状类是抽象的,声明了变量volume和area。
-
如果你关注Java Naming Conventions,它将极大地提高可读性,尤其是类应该是
SentenceCase和变量/参数camelCase。
标签: java arrays methods instantiation