Search code examples
c#decorator

Why do I keep getting the abstract class's string? C#


When I print the first beverage out it is able to get the correct description of espresso. However the second I add a the decorator, I get issues and instead of returning "The darkest of Roasts, Mocha" I get "Unknown Beverage".

This is not homework it's from Head First Design Patterns 1st edition. However written in C# instead of Java.

Any thoughts?

Console.WriteLine(e.getDescription() + " $" + e.cost());

Beverage d = new DarkRoast();
d = new Mocha(d);

Console.WriteLine(d.getDescription() + " $" + d.cost());

public abstract class Beverage
{
    protected string description = "Unknown Beverage";
    public string getDescription()
    {
        return description;
    }
    public abstract double cost();
}
public abstract class CondimentDecorator : Beverage
{
    public Beverage beverage;
    protected abstract string getDescription();
}

public class Espresso : Beverage
{

    public Espresso() {
        description = "Espresso";
    }
    public override double cost()
    {
        return 1.99;
    }
}

public class DarkRoast : Beverage
{
    public DarkRoast()
    {
        description = "The Darkest of Roasts";
    }
    public override double cost()
    {
        return .99;
    }
}

public class Mocha : CondimentDecorator
{
    public Mocha(Beverage beverage)
    {
        this.beverage = beverage;
    }
    public override double cost()
    {
        return beverage.cost() + .20;
    }

    protected override string getDescription()
    {
        return (beverage.getDescription() + ", Mocha");
    }
}

Solution

  • After reading on the CS108 issue and this post: Difference between shadowing and overriding in C#?

    I did see that it was my access modifiers giving me issues. When I ended up changing my getDescription function to public virtual string getDescription()

    so that my CondimentDecorator was able to override it with public override abstract string getDescription();