java实例_多态 [长方形类Rect长方体类Cub添加抽象类 Shape]

代码实现

package Lab6;
import java.util.Scanner;

abstract class shape {
public abstract double area();
public abstract double peri();
}

class Rect extends shape
{
public int length;
public int width;


public void setdate(int length,int width)
{

this.length = length;
this.width = width;
}
public int getlength()
{
return length;

}
public int getwidth()
{
return width;
}

public double area(){
return this.length*this.width;
}
public double peri(){
return this.length*2+this.width*2;
}

}

class Cub extends Rect
{

private int Height;

public void setdate(int length,int width,int Height)
{
super.setdate(length, width);
this.Height = Height;
this.length = length;
this.width = width;
}
public int getHeight()
{
return Height;
}
public double getvol(){

return this.length*this.width*this.Height;
}
public double getarea(){

return 2*(this.length*this.width+this.Height*this.length+this.Height*this.width);
}
}

 


public class Lab6 {

public static void main(String[] args) {
// TODO 自动生成的方法存根
boolean x = true;
while(x)
{
System.out.println("请输入1或2选择长方形或长方体:");
Scanner in = new Scanner(System.in);
int n=in.nextInt();
switch (n)
{

case 1:
Rect shp_1 = new Rect();
System.out.println("请输入l,w:");
int l_1=in.nextInt();
int w_1=in.nextInt();
shp_1.setdate(l_1, w_1);
System.out.println("面积:"+shp_1.area()+" "+"周长:"+shp_1.peri());
break;
case 2:
Cub shp_2 = new Cub();
System.out.println("请输入l,w,h:");
int l_2=in.nextInt();
int w_2=in.nextInt();
int h_2=in.nextInt();
shp_2.setdate(l_2, w_2,h_2);
System.out.println("体积:"+shp_2.getvol()+" "+"表面积:"+shp_2.getarea());
break;

//default:

}
}
}
}

 

posted on 2019-06-25 18:48  小涛同志v5  阅读(402)  评论(0编辑  收藏  举报

导航