Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.List;
- public class Test {
- public static class Canvas {
- private List<GeometricFigure> figures;
- public Canvas() {
- figures= new ArrayList<GeometricFigure>();
- }
- public void print() {
- for (GeometricFigure figure : figures) {
- System.out.println(figure.getGirth());
- }
- }
- public void addFigure(GeometricFigure figure) {
- figures.add(figure);
- }
- }
- public static interface GeometricFigure {
- public Double getGirth();
- }
- public static class Square implements GeometricFigure {
- private double sideLength;
- public Square(double sideLength) {
- this.sideLength= sideLength;
- }
- @Override
- public Double getGirth() {
- return sideLength * 4;
- }
- }
- public static class Circle implements GeometricFigure {
- private double diameter;
- public Circle(double diameter) {
- this.diameter= diameter;
- }
- @Override
- public Double getGirth() {
- return Math.PI * diameter;
- }
- }
- public static void main(String... args) {
- Canvas c= new Canvas();
- //Canvas#addFigure takes as an input argument GeometricFigure and we are passing Square and Circle
- //That is because both are implementing GeometricFigure interface, so we don't care what actual
- //implementations we pass in, as long as the interface is respected.
- c.addFigure(new Square(4));
- c.addFigure(new Circle(4));
- //Prints 16 and 12.56 which is good. We don't care what are the implementations of the GeometricFigure
- //we only care about their girth
- c.print();
- //we add anonymously instantiated geometric figure
- c.addFigure(new GeometricFigure() {
- //We must override this method
- @Override
- public Double getGirth() {
- return 100.0;
- }
- });
- c.print();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement