java - 在 Java 中实现定义三种形状的类

标签 java class methods tostring

我认为我已经实现了这组说明中要求的所有内容:

设计并实现一组定义形状的三个类: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?

感谢您的帮助!

最佳答案

SphereCone 中实现 toString() 方法。在这些 toString 方法中,输入特定于这些类以及父类(super class)调用 super.toString()

的字段的详细信息

对于 Cone,它会是这样的:

public String toString() {
     return height + super.toString();
}

关于java - 在 Java 中实现定义三种形状的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31495773/

相关文章:

java - 将 TreeMap 修剪为 n 个条目

java - 按钮放置和位置不起作用

c++ - 重载运算符以处理类对象?

javascript - 如何创建将方法添加到原型(prototype)并正确使用 "class"的 JavaScript 'this'

java - 在主程序中调用方法

Java Bean 约定

java - 如何在不使用Applet的情况下加密浏览器中的文本字段?

class - VB6中对象的赋值

java - 在 pom.xml 的 lib 文件夹中添加类路径和依赖项后,Maven 构建失败 NoClassDefFoundError

javascript - Jquery each 方法