Advertisement
Guest User

openClosed

a guest
Sep 22nd, 2019
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.34 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. interface Shape{
  4.     double getValue();
  5. }
  6.  
  7. class Circle implements Shape{
  8.     double radius;
  9.     Circle(double radius){
  10.         this.radius = radius;
  11.     }
  12.     public double getValue(){
  13.         return radius;
  14.     }
  15. }
  16.  
  17. class Square implements Shape{
  18.     double side;
  19.     Square(double side){
  20.         this.side = side;
  21.     }
  22.     public double getValue(){
  23.         return side;
  24.     }
  25. }
  26.  
  27. class CalculateAreaSummation{
  28.     ArrayList<Shape>arr = new ArrayList<>();
  29.     double total = 0;
  30.  
  31.     void addShape(Shape shape){
  32.         arr.add(shape);
  33.     }
  34.  
  35.     public double calcArea(){
  36.         this.total = 0;
  37.         for(Shape shape : arr){
  38.             if(shape instanceof Circle) total += Math.PI*shape.getValue()*shape.getValue();
  39.             if(shape instanceof Square) total += shape.getValue()*shape.getValue();
  40.         }
  41.         return total;
  42.     }
  43.  
  44.     void printOutput(){
  45.         System.out.println("total: " + total);
  46.     }
  47. }
  48.  
  49.  
  50. class OpenClosed{
  51.     public static void main(String[] args){
  52.         Shape circle = new Circle(5);
  53.         Shape square = new Square(10);
  54.  
  55.         CalculateAreaSummation sum = new CalculateAreaSummation();
  56.         sum.addShape(circle);
  57.         System.out.println(sum.calcArea());
  58.  
  59.         sum.addShape(square);
  60.         System.out.println(sum.calcArea());
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement