【Java】定义一个盒子类Box,包括3个私有变量(width,length,height),一个构造方法和showBox()方法。构造方法用来初始化变量,showBox()方法无参数,用于输出变量.
目录
题目:
定义一个盒子类Box
包括3个私有变量(width,length,height),一个构造方法和showBox()方法。
构造方法用来初始化变量,showBox()方法无参数,用于输出变量(width,length和height)
的值。
代码:
步骤
1.首先定义一个公共类Box
2.在类中定义三个私有变量:width,length和height。
3.定义一个构造方法
Box(double width,double length,double height),用来初始化这三个变量值。
4.定义了一个shouBox()方法,用于输出变量
package test2;
public class Box {
private double width;
private double length;
private double height;
public Box(double width,double length,double height){
this.width=width;
this.length=length;
this.height=height;
}
public void showBox(){
System.out.println("Box dimensions:width="+width+",length="+length+",height="+height);
}
}
package test2;
public class main {
public static void main(String[] args) {
Box b=new Box(1.5,2.0,3.0);
b.showBox();
}
}
这段代码创建了一个 Box 对象b,调用了其中的showBox()方法,输出该对象的宽,长和高
结果: