目的
掌握java语言对抽象类的定义、方法重写、多态等知识点的用法。
内容
输出一组图形的面积和、周长和,其中图形具备以下特征:
圆形:半径;
正方形形:边长;
三角形:三条边长;
输出内容如图:
代码实现
public abstract class Theshape {
double area,girth;
static double sumArea=0,sumGirth=0;
String name;
Theshape(String name){
this.name=name;
}
double getArea(){
return area;
}
double getGirth(){
return girth;
}
double getSumGirth(){
return sumGirth;
}
double getSumArea(){
return sumArea;
}
}
class Circle extends Theshape{
double r;
double PI=3.141592653;
Circle(String name,double r){
super(name);
this.r=r;
girth=2*PI*r;
area=PI*r*r;
sumGirth+=girth;
sumArea+=area;
}
void getmsg(){
System.out.println(name +",半径是:" + r +"面积是:"+area+"周长是:"+girth);
}
}
class Square extends Theshape{
double l;
double PI=3.141592653;
Square(String name,double l){
super(name);
this.l=l;
girth=4*l;
area=l*l;
sumGirth+=girth;
sumArea+=area;
}
void getmsg(){
System.out.println(name +",边长是:" + l +"面积是:"+area+"周长是:"+girth);
}
}
class Tringle extends Theshape{
double a,b,c;
double PI=3.141592653;
Tringle(String name,double a,double b,double c){
super(name);
this.a=a;
this.b=b;
this.c=c;
if(a+b<=c||a+c<=b||b+c<=a){
System.out.println("数字非法,不属于三角形");
}
else{
double p;
p=(a+b+c)/2;
area=Math.sqrt(p*(p-a)*(p-b)*(p-c));
girth=a+b+c;
sumGirth+=girth;
sumArea+=area;
}
}
void getmsg(){
System.out.println(name +",三边是:" +a+","+b+","+c +"面积是:"+area+"周长是:"+girth);
}
}
class test{
public static void main(String[] args) {
Circle circle=new Circle("圆形",10);
Square square1=new Square("正方形",10);
Square square2=new Square("正方形",20);
Tringle tringle1=new Tringle("三角形",10,10,10);
Tringle tringle2=new Tringle("三角形",10,10,15);
circle.getmsg();
square1.getmsg();
square2.getmsg();
tringle1.getmsg();
tringle2.getmsg();
System.out.println("总面积是:"+Theshape.sumArea);
System.out.println("总周长是:"+Theshape.sumGirth);
}
}