(1)定义一个类,描述一个矩形,包含有长、宽两种属性,和计算面积方法。
public class Jvcs {
private int Long; //长
private int wide; //宽
public Jvcs() { //无参
super();
}
public Jvcs(int aLong, int wide) { //有参
Long = aLong;
this.wide = wide;
}
public int getLong() {
return Long;
}
public void setLong(int aLong) {
Long = aLong;
}
public int getWide() {
return wide;
}
public void setWide(int wide) {
this.wide = wide;
}
//成员方法
public double product(){
return this.Long*this.wide;
}
}
(2)编写一个类,继承自矩形类,同时该类描述长方体,具有长、宽、高属性
public class Jvtj extends Jvcs{
//成员变量
private double height;
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
//定义新的成员方法体积
public double tiji(){
return this.getHeight()*this.getLong()*this.getWide();
}
}
(3)编写一个测试类,对以上两个类进行测试,创建一个长方体,定义其长、
宽、高,输出其底面积和体积。
public class Example {
public static void main(String[] args) {
//实例化矩形对象求面积
Jvcs g=new Jvcs();
g.setLong(10);
g.setWide(15);
System.out.println("矩形的长为:"+g.getLong()+"宽为:"+g.getWide());
System.out.println("矩形的面积为:"+g.product());
Jvtj c=new Jvtj();
c.setHeight(5);
c.setLong(6);
c.setWide(12);
System.out.println("矩形的高为:"+c.getHeight()+"宽为:"+c.getWide()+"长为:"+c.getLong());
System.out.println("矩形的体积为:"+c.tiji());
}
}
|