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教程中创建了上述程序。问题是我无法计算具有双数据类型的盒子的音量。运行时重载的方法解析以及类型提升如何工作?
程序结果显示如下:
volume is0.0
volume is0.0
volume is192
volume is192
其次,我感到困惑的方法重载的Java的概念,因为我知道,在方法重载,我们可以使用相同的方法名与不同的参数,但如我创建了卷方法,我不得不修改方法的名称(volume,vol),以便重载卷方法并获得答案。这是为什么?
重载'volume()' - *因为我知道在方法重载时,我们可以使用相同的方法名称与不同的参数* - 关键词是参数,您不能通过更改它们的返回来重载方法类型。 –
原因很明显:您将整数传递给构造函数,所以double值从不设置。他们总是零。 – duffymo