Guest User

Untitled

a guest
Jan 22nd, 2019
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.62 KB | None | 0 0
  1. public abstract class Shape {
  2. public abstract double area();
  3. public abstract double perimeter();
  4. }
  5.  
  6. public class Rectangle extends Shape {
  7. private final double width, length; //sides
  8.  
  9. public Rectangle() {
  10. this(1,1);
  11. }
  12. public Rectangle(double width, double length) {
  13. this.width = width;
  14. this.length = length;
  15. }
  16.  
  17. @Override
  18. public double area() {
  19. // A = w * l
  20. return width * length;
  21. }
  22.  
  23. @Override
  24. public double perimeter() {
  25. // P = 2(w + l)
  26. return 2 * (width + length);
  27. }
  28.  
  29. }
  30.  
  31. public class Circle extends Shape {
  32. private final double radius;
  33. final double pi = Math.PI;
  34.  
  35. public Circle() {
  36. this(1);
  37. }
  38. public Circle(double radius) {
  39. this.radius = radius;
  40. }
  41.  
  42. @Override
  43. public double area() {
  44. // A = π r^2
  45. return pi * Math.pow(radius, 2);
  46. }
  47.  
  48. public double perimeter() {
  49. // P = 2πr
  50. return 2 * pi * radius;
  51. }
  52. }
  53.  
  54. public class Triangle extends Shape {
  55. private final double a, b, c; // sides
  56.  
  57. public Triangle() {
  58. this(1,1,1);
  59. }
  60. public Triangle(double a, double b, double c) {
  61. this.a = a;
  62. this.b = b;
  63. this.c = c;
  64. }
  65.  
  66. @Override
  67. public double area() {
  68. // Heron's formula:
  69. // A = SquareRoot(s * (s - a) * (s - b) * (s - c))
  70. // where s = (a + b + c) / 2, or 1/2 of the perimeter of the triangle
  71. double s = (a + b + c) / 2;
  72. return Math.sqrt(s * (s - a) * (s - b) * (s - c));
  73. }
  74.  
  75. @Override
  76. public double perimeter() {
  77. // P = a + b + c
  78. return a + b + c;
  79. }
  80. }
  81.  
  82. public class TestShape {
  83. public static void main(String[] args) {
  84.  
  85. // Rectangle test
  86. double width = 5, length = 7;
  87. Shape rectangle = new Rectangle(width, length);
  88. System.out.println("Rectangle width: " + width + " and length: " + length
  89. + "\nResulting area: " + rectangle.area()
  90. + "\nResulting perimeter: " + rectangle.perimeter() + "\n");
  91.  
  92. // Circle test
  93. double radius = 5;
  94. Shape circle = new Circle(radius);
  95. System.out.println("Circle radius: " + radius
  96. + "\nResulting Area: " + circle.area()
  97. + "\nResulting Perimeter: " + circle.perimeter() + "\n");
  98.  
  99. // Triangle test
  100. double a = 5, b = 3, c = 4;
  101. Shape triangle = new Triangle(a,b,c);
  102. System.out.println("Triangle sides lengths: " + a + ", " + b + ", " + c
  103. + "\nResulting Area: " + triangle.area()
  104. + "\nResulting Perimeter: " + triangle.perimeter() + "\n");
  105. }
  106. }
Add Comment
Please, Sign In to add comment