长方形--父类
public class cfx {//长方形类---父类
private double chang;
private double kuang;
public cfx() {
}
public cfx(double chang,double kuang) {
this.chang=chang;
this.kuang=kuang;
}
public double getChang() {
return chang;
}
public void setChang(double chang) {
this.chang = chang;
}
public double getKuang() {
return kuang;
}
public void setKuang(double kuang) {
this.kuang = kuang;
}
public double zc() {//长方形的周长
double zc=2*(chang+kuang);
return zc;
}
public double mj() {//长方形的面积
double mj=chang*kuang;
return mj;
}
public void disp() {
System.out.println("长方形的周长是"+zc());
System.out.println("长方形的面积是"+mj());
}
}
长方体类--子类
public class cft extends cfx{//长方体类----子类
private double height;
public cft() {
}
public cft(double chang,double kuang,double height) {
super(chang, kuang);
this.height=height;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double bmj() {
double bmj=(getChang()*getKuang()+getChang()*height+getKuang()*height)*2;
return bmj;
}
public double tj() {
double tj=getChang()*getKuang()*height;
return tj;
}
public void disp() {
System.out.println("长方体的表面积是"+bmj());
System.out.println("长方体的体积是"+tj());
}
}
测试类
public class cfxtest {
public static void main(String[] args) {
// TODO 自动生成的方法存根
Scanner sc=new Scanner(System.in);
double a,b,h;
System.out.println("请输入长方形和长方体的长");
a=sc.nextDouble();
System.out.println("请输入长方形和长方体的宽");
b=sc.nextDouble();
cfx cfx=new cfx(a,b);//长方形
System.out.println("请输入长方体的高");
h=sc.nextDouble();
cft cft=new cft(a,b,h);//长方体
cfx.disp();
cft.disp();
cfx cftCfx=new cft(a,b,h);//利用多态实现长方体,但属性值是长方形的
cftCfx.disp();
}
}