Guest User

Untitled

a guest
Jun 25th, 2013
59
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.util.ArrayList;
  2. import java.util.List;
  3.  
  4. public class Test {
  5.  
  6.     public static class Canvas {
  7.  
  8.         private List<GeometricFigure> figures;
  9.  
  10.         public Canvas() {
  11.             figures= new ArrayList<GeometricFigure>();
  12.         }
  13.  
  14.         public void print() {
  15.             for (GeometricFigure figure : figures) {
  16.                 System.out.println(figure.getGirth());
  17.             }
  18.         }
  19.  
  20.         public void addFigure(GeometricFigure figure) {
  21.             figures.add(figure);
  22.         }
  23.        
  24.     }
  25.  
  26.     public static interface GeometricFigure {
  27.  
  28.         public Double getGirth();
  29.  
  30.     }
  31.    
  32.     public static class Square implements GeometricFigure {
  33.  
  34.         private double sideLength;
  35.  
  36.         public Square(double sideLength) {
  37.             this.sideLength= sideLength;
  38.         }
  39.        
  40.         @Override
  41.         public Double getGirth() {
  42.             return sideLength * 4;
  43.         }
  44.        
  45.     }
  46.    
  47.     public static class Circle implements GeometricFigure {
  48.  
  49.         private double diameter;
  50.  
  51.         public Circle(double diameter) {
  52.             this.diameter= diameter;
  53.         }
  54.        
  55.         @Override
  56.         public Double getGirth() {
  57.             return Math.PI * diameter;
  58.         }
  59.        
  60.     }
  61.    
  62.     public static void main(String... args) {
  63.         Canvas c= new Canvas();
  64.         //Canvas#addFigure takes as an input argument GeometricFigure and we are passing Square and Circle
  65.         //That is because both are implementing GeometricFigure interface, so we don't care what actual
  66.         //implementations we pass in, as long as the interface is respected.
  67.         c.addFigure(new Square(4));
  68.         c.addFigure(new Circle(4));
  69.         //Prints 16 and 12.56 which is good. We don't care what are the implementations of the GeometricFigure
  70.         //we only care about their girth
  71.         c.print();
  72.        
  73.         //we add anonymously instantiated geometric figure
  74.         c.addFigure(new GeometricFigure() {
  75.  
  76.             //We must override this method
  77.             @Override
  78.             public Double getGirth() {
  79.                 return 100.0;
  80.             }
  81.         });
  82.         c.print();
  83.     }
  84.  
  85. }
RAW Paste Data