class Trangle
{
double sideA,sideB,sideC,area,length;
boolean boo;
public Trangle(double a,double b,double c)//三角形的三边abc
{
sideA=a;
sideB=b;
sideC=c;
if(a+b>c&&b+c>a&&a+c>b)//abc构成三角形的条件表达式
boo=true;//成立给boo赋值true
else
boo=false;//不成立给boo赋值false
}
double getLength()//求周长
{
return (sideA+sideB+sideC);
}
public double getArea()//求面积
{
if(boo)
{
double p=(sideA+sideB+sideC)/2.0;
area=Math.sqrt(p*(p-sideA)*(p-sideB)*(p-sideC));
return area;
}
else
{
System.out.println("这不是一个三角型,不能计算面积");
return 0;
}
}
public void setABC(double a,double b,double c)//给三角形修改边长
{
sideA=a;
sideB=b;
sideC=c;
if(a+b>c&&b+c>a&&a+c>b)
{
boo=true;
}
else
boo=false;
}
}
class Lader//定义类梯形
{
public double above,bottom,height,area;
public Lader(double a,double b,double h)//构造函数
{
above=a;
bottom=b;
height=h;
}
double setArea()//求梯形面积
{
return ((above+bottom)*height/2.0);
}
}
class Circle//定义圆类
{
double redius,area,length;
public Circle(double r)//构造函数
{
redius=r;
}
double getLength()//求圆的周长
{
return (2*3.14*redius);
}
double getArea()//求圆的面积
{
return (3.14*redius*redius);
}
}
public class AreaandLength
{
public static void main(String arg[])
{
double length,area;
Circle circle=null;
Trangle trangle;
Lader lader;
circle=new Circle(10);//创建对象
trangle=new Trangle(3,4,5);
lader=new Lader(3,4,10);
length=circle.getLength();
System.out.println("圆的周长为:"+length);
area=circle.getArea();
System.out.println("圆的面积为:"+area);
length=trangle.getLength();
System.out.println("三角形的周长为:"+length);
area=trangle.getArea();
System.out.println("三角形的面积为:"+area);
area=lader.setArea();
System.out.println("梯形的面积为:"+area);
trangle.setABC(0,0,0);
area=trangle.getArea();
System.out.println("三角形的面积为:"+area);
}
}
运行结果:
三角型 梯形 圆 在类中封装
最新推荐文章于 2022-10-03 16:43:23 发布