第9次作业--接口及接口回调
package Test2; 2 import java.util.Scanner; 3 4 interface Shape{//图形类 5 double getArea(); 6 } 7 8 class Rectangle implements Shape {//长方形类 9 double width; 10 double length; 11 12 public Rectangle(double width,double length) { 13 this.width = width; 14 this.length = length; 15 } 16 17 @Override 18 public double getArea() { 19 // TODO Auto-generated method stub 20 return width*length; 21 } 22 } 23 24 class Square2 extends Rectangle{//正方形类 25 26 public Square2(double width) { 27 super(width, width); 28 // TODO Auto-generated constructor stub 29 } 30 public double getArea() { 31 return width* width; 32 } 33 } 34 35 class Triangle implements Shape{//三角形类 36 double length1; 37 double length2; 38 double length3; 39 public Triangle(double length1,double length2,double length3) { 40 this.length1 = length1; 41 this.length2 = length2; 42 this.length3 = length3; 43 } 44 public double getArea() { 45 double num = (length1+length2+length3)/2; 46 return Math.sqrt(num*(num-length1)*(num-length2)*(num-length3)); 47 } 48 } 49 50 class Prism { 51 Shape shape; 52 double hight; 53 public Prism(Shape shape,double hight) {//棱柱类 54 this.hight = hight; 55 this.shape = shape; 56 } 57 public double getVolumn() { 58 return shape.getArea()*hight; 59 } 60 public void setShape(Shape shape) { 61 this.shape = shape; 62 } 63 } 64 65 class Circle implements Shape{//圆类 66 double r; 67 final double PI=3.14; 68 Circle(double r){ 69 this.r=r; 70 } 71 public double getArea(){ 72 return PI*r*r; 73 } 74 } 75 76 class Factory{//工厂类 77 Shape shape; 78 char gc; 79 Factory(char ch){ 80 this.gc = ch; 81 } 82 public Shape getShape(){ 83 switch(gc){ 84 case 't':shape=new Triangle(1,2,3);break; 85 case 'r':shape=new Rectangle(4,5);break; 86 case 's':shape=new Square2(6);break; 87 case 'c':shape=new Circle(7);break; 88 } 89 return shape; 90 } 91 public char getgc(){ 92 return gc; 93 } 94 public void setShape(Shape shape){ 95 this.shape=shape; 96 } 97 public void setCh(char ch){ 98 this.gc=ch; 99 } 100 } 101 102 public class tt {//主函数 103 104 public static void main(String[] args) { 105 for(int i = 0;i<4;i++) { 106 Scanner sc = new Scanner(System.in); 107 String str = sc.next(); 108 char ch = str.charAt(0); 109 Factory fa=new Factory(ch); 110 Prism pri=new Prism(fa.getShape(),6); 111 pri.setShape(fa.getShape()); 112 double vol=pri.getVolumn(); 113 System.out.println(vol); 114 } 115 116 } 117 }