Let's take a look and understand this piece of code:
coffee c = new simplecoffee(); System.out.println("Cost:" + c.getCost());
- Create a simplecoffee object and assign it
c . c declared the type of coffee (no problem, since simplecoffee is an implementation of the coffee interface).
Next step:
c = new milk(c); System.out.println("Cost:" + c.getCost());
- Create a milk object and assign milk to
c to the new object (overwrite the old value c ). - milk extends the
coffeedecorator abstract class, which also implements the coffee interface. - The simplecoffee object at the top is assigned to the instance variable inside the milk class.
Consider the implementation of milk.getCost () , which is called before the last print:
public double getCost(){ return super.getCost() + 0.5; }
super.getCost() is implemented in the coffeedecorator class. It simply calls the getCost() method of the coffee instance inside.- In our case, it is simplecoffee , which costs 1.
- Milk costs 0.5.
So you come together 1.5.
Greets Alan.
source share