实验四 (1):定义一个形状类(Shape)方法:计算周长,计算面积

时间:2022-09-19 12:51:45

(1)定义一个形状类(Shape)方法:计算周长,计算面积
子类:
矩形类(Rectangle) :额外的方法:differ() 计算长宽差
圆形类(Circle)
三角形类(Triangle)
正方形类(Square) 矩形的子类
生成几个不同的形状对象,放在一个Shape类型的数组里,分别求每个形状的周长和面积。如果形状对象是一个矩形,且不是正方形,则计算长宽差。

 package com.tiger.practice;

  class Shape {

     public double length(){
return ;
} public double area() {
return ;
}
} class Rectangle extends Shape { private double width;
private double height; public Rectangle(double height,double width) {
this.height=height;
this.width = width;
} @Override
public double length() {
// TODO Auto-generated method stub
return *(width+height);
} @Override
public double area() {
// TODO Auto-generated method stub
return width*height;
} public double differ() {
return Math.abs(height-width);
} } class Square extends Rectangle { public double edge; public Square(double edge) {
super(edge,edge);
setEdge(edge);
// TODO Auto-generated constructor stub
} public double getEdge() {
return edge;
} public void setEdge(double edge) {
this.edge = edge;
}
} class Triangle extends Shape {
private double a;
private double b;
private double c; public Triangle(double a,double b,double c) {
this.a= a;
this.b = b;
this.c = c;
} @Override
public double length() {
// TODO Auto-generated method stub
return a+b+c;
} @Override
public double area() {
double p= (a+b+c)/;
// TODO Auto-generated method stub
return Math.sqrt(p*(p-a)*(p-b)*(p-c));
}
} class circle extends Shape{
private double r;
public circle(double r){
this.r = r;
}
public double length(){
return 3.1415**r;
}
public double area(){
return 3.1415*r*r;
} } public class shapes { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Shape[] shapes= {
new Rectangle(,),
new circle(),
new Square(),
new Triangle(, , )
};
for(int i=;i<shapes.length;i++) {
double length=shapes[i].length();
double area=shapes[i].area();
if(shapes[i]instanceof circle) {
System.out.println("Shape("+(i+)+"): "+
"length"+String.format("%.4f", length)+",area"
+String.format("%.4f", area));
}
else {
System.out.println("Shape("+(i+)+"): "+
"length"+length+",area"+area);
if(shapes[i]instanceof Rectangle) {
Rectangle r=(Rectangle)shapes[i];
System.out.println("长宽差是: "+r.differ());
}
}
}
} }