class Box {
private double width;
private double height;
private double depth;
// compute and return volume
double volume() {
return width * height * depth;
}
public void setWidth(double width){
this.width=width;
}
public void setHeight(double height){
this.height=height;
}
public void setDepth(double depth){
this.depth=depth;
}
}
public class BoxDemo2 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
mybox1.setWidth(10);
mybox1.setHeight(20);
mybox1.setDepth(15);
/* assign different values to mybox2's
instance variables */
mybox2.setWidth(3);
mybox2.setHeight(6);
mybox2.setDepth(9);
// get volume of first box
vol = mybox1.volume();
System.out.println("The volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("The volume is " + vol);
}
}
(1)代码不能成功编译。
由报错截图可以看出,报错的代码行依次为第24,25,26,30,31,32行代码。其原因是因为当我们在变量前加上private后,这三个变量成为私有属性,此时它们只能被Box类中的成员访问,无法被BoxDemo2类中的成员访问。
(2)于是我们在Box类中加入如下代码段:
public void setWidth(double width){
this.width=width;
}
public void setHeight(double height){
this.height=height;
}
public void setDepth(double depth){
this.depth=depth;
}
并且在BoxDemo2类中修改如下代码段:
mybox1.setWidth(10);
mybox1.setHeight(20);
mybox1.setDepth(15);
mybox2.setWidth(3);
mybox2.setHeight(6);
mybox2.setDepth(9);
之所以这样修改,是因为被私有访问修饰符private声明的变量只能通过类中公共的set方法被外部类访问,于是我们通过setXXXX(double XXXX)来设置XXXX的值。相应的,我们需要把BoxDemo2中的XXXX修改为setXXXX,等号修改为括号来调用这三个对象。