//程序名:Boy.java
/*
要求:
1)小男孩类包括小男孩的姓名、他拥有的图形。
2)男孩拥有的图形要用抽象类实现。
3)创建至少三个小男孩对象,要求求三个小男孩拥有的图形的面积总和。
**/
//程序员:李显福
class Boy
{
String name;
Shape tuxing;
Boy(String name,Shape tuxing)
{
this.name=name;
this.tuxing=tuxing;
}
void boyshow()
{
System.out.println("小男孩的姓名是:"+name);
System.out.println(name+"有个图形,图形的形状是"+tuxing);
System.out.println("");//输出空一行。
}
}
class Shape
{
String name;
double s;
Shape(String name)
{
this.name=name;
}
public double area()
{
return s;
}
}
//圆类
class Circle extends Shape
{
private double r;
Circle(String name,double r)
{
super(name);
this.r=r;
}
public double area()
{
return 3.14*r*r;
}
public String toString()
{
return name+"\n它的半径是:"+r+"\n它的面积是:"+3.14*r*r;
}
}
//三角形类
class Triangle extends Shape
{
private double a;
private double b;
private double c;
Triangle(String name,double a,double b,double c)
{
super(name);
this.a=a;
this.b=b;
this.c=c;
}
public boolean isTriangle()
{
return (a+b>c)&&(a+c>b)&&(b+c>a);
}
public double area()
{
double s=0.5*(a+b+c);
return Math.sqrt(s*(s-a)*(s-b)*(s-c));
}
public String toString()
{
return name+"\n"+name+"的三条边分别是:"+a+"\t"+b+"\t"+c+"\n"+name+"的面积是:"+area();
}
}
//矩形
class Juxing extends Shape
{
private double a;
private double b;
Juxing(String name,double a,double b)
{
super(name);
this.a=a;
this.b=b;
}
public double area()
{
return a*b;
}
public String toString()
{
return name+"\n它的长是:"+a+"\n它的宽是:"+b+"\n它的面积是:"+a*b;
}
}
class DemoBoy
{
public static void main(String args[])
{
Circle c1=new Circle("圆",2);
Boy b1=new Boy("李显福",c1);
b1.boyshow();
Triangle t1=new Triangle("三角形",3,4,5);
Boy b2=new Boy("李君逸",t1);
b2.boyshow();
Juxing j1=new Juxing("长方形",10,5);
Boy b3=new Boy("李元霸",j1);
b3.boyshow();
double s1=c1.area();
double s2=t1.area();
double s3=j1.area();
System.out.println("面积和是:"+(s1+s2+s3));
}
} |
|