【发布时间】:2016-12-11 09:22:15
【问题描述】:
package arunjava;
public class sample3 {
public static void main(String[] args) {
Box25 b1 = new Box25();
Box25 b2 = new Box25();
b1.Dimension(25, 32, 65);
b2.Dimension(25, 45, 62);
System.out.println("volume is" + b1.volume());
System.out.println("volume is" + b2.volume());
b1.Dimension(4, 6, 8);
b2.Dimension(6, 8, 4);
System.out.println("volume is" + b1.vol());
System.out.println("volume is" + b2.vol());
}
}
class Box25 {
double height, width, depth;
int height1, width1, depth1;
public void Dimension(double height, double width, double depth) {
this.height = height;
this.width = width;
this.depth = depth;
}
public void Dimension(int height1, int width1, int depth1) {
this.height1 = height1;
this.width1 = width1;
this.depth1 = depth1;
}
double volume() {
return height * depth * width;
}
int vol() {
return height1 * depth1 * width1;
}
}
我在我的 Java 教程中创建了上述程序。问题是我无法计算具有 double 数据类型的盒子的体积。
程序结果显示如下:
volume is0.0
volume is0.0
volume is192
volume is192
其次,我对 Java 方法重载的概念感到困惑,因为我知道在方法重载中我们可以使用具有不同参数的相同方法名称,但是在创建卷方法时,我不得不修改方法的名称(volume,vol),从而重载volume方法并得到答案。为什么会这样?
【问题讨论】:
-
关于重载
volume()-- 我知道在方法重载中我们可以使用相同的方法名和不同的参数 -- 关键字是参数,你可以'不要通过改变返回类型来重载方法。 -
原因很明显:您将整数传递给构造函数,因此永远不会设置双精度值。它们始终为零。
标签: java methods int double overloading