我认为我已经实现了这组说明中要求的所有内容:
设计并实现一组定义形状的三个类:RoundShape、Sphere、Cone。对于每个类,存储有关其大小的基本数据,并提供访问和修改此数据的方法。此外,提供适当的方法来计算球体和圆锥体的面积和体积。在您的设计中,请考虑形状如何相关以及可以在何处实现继承。不要创建重复的实例变量。创建一个 main 方法,实例化 2 个 Sphere 对象(任意参数)、2 个 Cone 对象(任意参数),使用 ToString() 显示它们,更改每个对象中的一个参数(您的选择),然后再次显示它们。
这是我的代码:
class RoundShape{
double shape = 9;
double radius = 4;
int cone1 = 3;
int sphere1;
public String toString(){
return " the man" + cone1 + "this also" + sphere1;
}
}
//--------------------------------------------------------------
// class Sphere that extends RoundShape
//--------------------------------------------------------------
class Sphere extends RoundShape{
double getArea(){
double area = 4 * Math.PI * Math.pow(radius, 2);
return area;
} // end of getArea
double getVolume(){
double volume = (4/3) * Math.PI * Math.pow(radius, 3);
return volume;
} // end of getVolume
} // end of the class Sphere
//---------------------------------------------------------------
// class Cone that extends RoundShape
//---------------------------------------------------------------
class Cone extends RoundShape{
double height = 8;
double getArea(){
double area = Math.PI * radius * (radius + Math.sqrt(Math.pow(height, 2) + Math.pow(radius, 2)));
return area;
} // end of getArea for Cone
double getVolume(){
double volume = Math.PI * Math.pow(radius, 2) * (height/3);
return volume;
} // end of getVolume for Cone
} // end of the class Cone
public class Murray_A03A4 {
public static void main(String[] args) {
Sphere sphere1 = new Sphere();
sphere1.getArea();
sphere1.getVolume();
System.out.println(sphere1);
Cone cone1 = new Cone();
cone1.getArea();
cone1.getVolume();
System.out.println(cone1);
} // End of class header
} // End of method header
我的主要问题是,如何从 main 方法中的内容引用 toString 方法?此外,toString 是否在正确的类中找到,或者我应该将其放入新类中,还是应该为每个类创建一个 toString?
感谢您的帮助!
最佳答案
在 Sphere
和 Cone
中实现 toString()
方法。在这些 toString
方法中,输入特定于这些类以及父类(super class)调用 super.toString()
对于 Cone,它会是这样的:
public String toString() {
return height + super.toString();
}
关于java - 在 Java 中实现定义三种形状的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31495773/