实验四 :定义一个形状类(Shape)方法:计算周长,计算面积
Posted CheeseIce
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了实验四 :定义一个形状类(Shape)方法:计算周长,计算面积相关的知识,希望对你有一定的参考价值。
(1)定义一个形状类(Shape)方法:计算周长,计算面积
子类:
矩形类(Rectangle) :额外的方法:differ() 计算长宽差
圆形类(Circle)
三角形类(Triangle)
正方形类(Square) 矩形的子类
生成几个不同的形状对象,放在一个Shape类型的数组里,分别求每个形状的周长和面积。如果形状对象是一个矩形,且不是正方形,则计算长宽差。
1 package com.tiger.practice; 2 3 class Shape { 4 5 public double length(){ 6 return 0; 7 } 8 9 public double area() { 10 return 0; 11 } 12 } 13 14 class Rectangle extends Shape { 15 16 private double width; 17 private double height; 18 19 20 public Rectangle(double height,double width) { 21 this.height=height; 22 this.width = width; 23 } 24 25 @Override 26 public double length() { 27 // TODO Auto-generated method stub 28 return 2*(width+height); 29 } 30 31 @Override 32 public double area() { 33 // TODO Auto-generated method stub 34 return width*height; 35 } 36 37 public double differ() { 38 return Math.abs(height-width); 39 } 40 41 } 42 43 class Square extends Rectangle { 44 45 public double edge; 46 47 public Square(double edge) { 48 super(edge,edge); 49 setEdge(edge); 50 // TODO Auto-generated constructor stub 51 } 52 53 public double getEdge() { 54 return edge; 55 } 56 57 public void setEdge(double edge) { 58 this.edge = edge; 59 } 60 } 61 62 class Triangle extends Shape { 63 private double a; 64 private double b; 65 private double c; 66 67 public Triangle(double a,double b,double c) { 68 this.a= a; 69 this.b = b; 70 this.c = c; 71 } 72 73 @Override 74 public double length() { 75 // TODO Auto-generated method stub 76 return a+b+c; 77 } 78 79 @Override 80 public double area() { 81 double p= (a+b+c)/2; 82 // TODO Auto-generated method stub 83 return Math.sqrt(p*(p-a)*(p-b)*(p-c)); 84 } 85 } 86 87 class circle extends Shape{ 88 private double r; 89 public circle(double r){ 90 this.r = r; 91 } 92 public double length(){ 93 return 3.1415*2*r; 94 } 95 public double area(){ 96 return 3.1415*r*r; 97 } 98 99 } 100 101 public class shapes { 102 103 /** 104 * @param args 105 */ 106 public static void main(String[] args) { 107 // TODO Auto-generated method stub 108 Shape[] shapes= { 109 new Rectangle(5,10), 110 new circle(5), 111 new Square(3), 112 new Triangle(3, 4, 5) 113 }; 114 for(int i=0;i<shapes.length;i++) { 115 double length=shapes[i].length(); 116 double area=shapes[i].area(); 117 if(shapes[i]instanceof circle) { 118 System.out.println("Shape("+(i+1)+"): "+ 119 "length"+String.format("%.4f", length)+",area" 120 +String.format("%.4f", area)); 121 } 122 else { 123 System.out.println("Shape("+(i+1)+"): "+ 124 "length"+length+",area"+area); 125 if(shapes[i]instanceof Rectangle) { 126 Rectangle r=(Rectangle)shapes[i]; 127 System.out.println("长宽差是: "+r.differ()); 128 } 129 } 130 } 131 } 132 133 }
以上是关于实验四 :定义一个形状类(Shape)方法:计算周长,计算面积的主要内容,如果未能解决你的问题,请参考以下文章