目的
掌握类的结构,对象的引用,熟悉属性、方法的使用。
要求
- 建立一个类,
① 矩形的属性长、宽、高、面积、体积分别为length, width、height,S、L;
② 方法setBox( ),设置length,width和height的初始值,
③ 方法getArea( ),计算矩形的面积S。
④ 方法getL( ),计算矩形的体积L。- 在主类的main方法中,输出矩形的长、宽、高和面积、体积。
- 增加三个构造方法,对长方体进行初始化。
- 对构造方法分别进行测试。
代码
public class 长方体
{
int length,width,height,S,L;
//初始化
public void setBox(int l,int w,int h)
{
length=l;
width=w;
height=h;
}
public void setBox()
{
length=7;
width=8;
height=9;
}
//面积
public void getArea()
{
S=2*(length*width+width*height+length*height);
}
//体积
public void getL()
{
L=length*width*height;
}
//显示
public void showinformation()
{
System.out.println("length="+length);
System.out.println("wight="+width);
System.out.println("height="+height);
}
public void showarea()
{
System.out.println("长方体的面积为"+S);
}
public void showL()
{
System.out.println("长方体的体积为"+L);
}
public static void main(String[] args)
{
长方体 a;
a=new 长方体();
a.setBox(2,3,4);
System.out.println("长方体A:");
a.showinformation();
a.getArea();
a.showarea();
a.getL();
a.showL();
System.out.println("长方体B:");
长方体 b;
b=new 长方体();
b.length=3;
b.height=4;
b.width=5;
b.showinformation();
b.getArea();
b.showarea();
b.getL();
b.showL();
System.out.println("长方体C:");
长方体 c;
c=new 长方体();
c.setBox();
c.showinformation();
c.getArea();
c.showarea();
c.getL();
c.showL();
}
}