如何聚合抽象类?

时间:2015-11-25 20:20:02

标签: java abstract aggregation

所以我试图在两个类之间实现聚合关系。但是,我对如何使用抽象类实现它感到困惑。 有什么建议吗?

Beverage.java

    public class Beverage {

        private Size size;
        private SizeFactor sizeCost;
        private String description; 

        public Beverage(){}

        public Size getSize(){
            return size;
        }

        public SizeFactor getSizeCost(){
            return sizeCost;
        }

        public String getDescription(){
            return description;
        }

        public void setSize(Size s){
            size = s;
        }

        public void setSizeCost(SizeFactor cost){
            sizeCost = cost;
        }

        public double cost(){
            return sizeCost.sizeCost(size);
        }

    }

BeverageWithIngredient.java

   public abstract class BeverageWithIngredient extends Beverage {

   private Beverage drink = new Beverage();

   public abstract String getDescription();
   public abstract double cost();

}

基本上,这就是我想要做的事情:

UML

1 个答案:

答案 0 :(得分:1)

您必须将Beverage注入BeverageWithIngredient

public abstract class BeverageWithIngredient extends Beverage {

   private Beverage drink;

   public BeverageWithIngredient(Beverage drink) {
       this.drink = drink;
   }

   public abstract String getDescription();
   public abstract double cost();
}