请解释这个 JAVA 程序的意外输出

时间:2021-04-20 16:48:43

标签: java

在下面的程序中,我只是尝试为 as Circle circ 创建一个简单的类,然后尝试从它 cylind 继承一个 Cylinder。我定义了几种方法来找到这些几何对象的周长、面积和体积,但我经常得到错误的答案。我花了好几个小时才找到错误,但我找不到它。我是初学者,所以我想我可能错过了一些东西。请帮忙。

package com.company;
class circ {
    int radius;
    public circ(int radius) {
        this.radius = radius;
    }
}
class cylind extends circ{
    int height;
    double area = (2*Math.PI * radius * ( radius + height ));
    double volume = (Math.PI * radius *radius * height );
    public cylind(int radius, int height) {
        super(radius);
        this.height = height;
    }
    public void area() {
        System.out.println("Total Surface Area = " + this.area);
    }
    public void volume(){
        System.out.println("Volume = " + this.volume);
    }
}
class Trial_and_error_2 {
    public static void main(String[] args) {
        cylind b =new cylind(10,45);
        System.out.println(b.radius);
        System.out.println(b.height);
        System.out.println(2*Math.PI * b.radius * ( b.radius + b.height ));
        System.out.println(Math.PI * b.radius *b.radius * b.height );
        b.area();
        b.volume();
    }
}

输出:我已经使用 ----> 来解释输出和问题。

10   ---> Radius 
45   ---> height 
3455.7519189487725 ---> Surface area calculated in the main block
14137.16694115407  ---> Volume calculated in the main block
Total Surface Area = 628.3185307179587  ---> Wrong values of Surface area printed by the method of class THIS IS THE PROBLEM.
Volume = 0.0             ---> Wrong values of volume printed by the method of class THIS IS THE PROBLEM.

2 个答案:

答案 0 :(得分:1)

在调用构造函数之前初始化实例变量“area”和“volume”。这就是为什么您会得到 volume = 0,因为发生这种情况时高度为 0。

答案 1 :(得分:0)

您的字段计算将在构造函数之前执行。

解决办法: 只需将计算移至构造函数:

public Cylinder(int radius, int height) {
    super(radius);
    this.height = height;
    area = 2*Math.PI * radius * (radius + height);
    volume = Math.PI * radius *radius * height;
}

另外,我建议使用首字母大写的完整类名。

相关问题