public class Blue implements Colour { @Override public void desc() { System.out.println("蓝色"); } } public class Red implements Colour { @Override public void desc() { System.out.println("红色"); } } public class Yellow implements Colour { @Override public void desc() { System.out.println("黄色"); } } public abstract class Graphical { private Colour colour;
public Graphical(Colour colour) { this.colour = colour; }
abstract void desc(); public Colour getColour(){ return colour; } }
public class Rectangle extends Graphical {
public Rectangle(Colour colour){ super(colour); } @Override public void desc() { System.out.println("长方形"); getColour().desc(); } }
public class Square extends Graphical {
public Square(Colour colour){ super(colour); } @Override public void desc() { System.out.println("正方形"); getColour().desc(); } }
public class Triangle extends Graphical {
public Triangle(Colour colour) { super(colour); }
@Override public void desc() { System.out.println("三角形"); getColour().desc(); } } public class Main { public static void main(String[] args) { Rectangle rectangle = new Rectangle(new Blue()); rectangle.desc(); } }