Possible Repeat: Why my Virtual method is not overriden?
I’ve been going through the Head First Design Patterns. On a side note, I started this book as a prerequisite to Code Complete 2. Anyway, I’m working with the Decorator pattern (the chapter can actually even be read online).
So, I have 4 classes:
- Beverage Class – Abstract
- Espresso Class – Inherits Beverage
- BeverageDecorator Class – Abstract
- Mocha Class – Inherits Beverage Decotrator
Here is the source code for classes 1, 3, 4.
Beverage Class:
public abstract class Beverage
{
public Beverage()
{
Description = "Unknown Beverage";
}
public String getDescription()
{
return Description;
}
public abstract double cost();
public String Description { get; set; }
}
BeverageDecorator Class:
public abstract class BeverageDecorator : Beverage
{
public new abstract String getDescription();
}
Mocha Class:
public class Mocha : BeverageDecorator
{
Beverage beverage;
public Mocha(Beverage beverage)
{
this.beverage = beverage;
}
public override string getDescription()
{
return beverage.Description + ", Mocha";
}
public override double cost()
{
return beverage.cost() + .20;
}
}
So they are pretty straight-forward. Then when I put this code in the Main() method I keep getting an “Unknown Beverage” description.
static void Main(string[] args)
{
Beverage beverage = new Espresso();
beverage = new Mocha(beverage);
Console.WriteLine(beverage.Description +
" $" + beverage.cost());
Console.Read();
}
Mocha goes from the class it inherits – Beverage Decorator – to the class above that – Beverage Class. Even though I have the method in the Beverage Decorator and I override it. Why is this happening? I know it has something to do with being abstract classes but I just can’t seem to figure it out.
Well, there are two problems. Firstly, it looks like your
Descriptionproperty should callgetDescriptionrather than the other way round. And thengetDescriptionneeds to be virtual in theBeverageclass and overridden inBeverageDecoratorrather than hidden.It doesn’t help that your code looks like a mixture of C# and Java. For example, do you really need a
Descriptionproperty and agetDescriptionmethod? Admittedly it’s slightly tricky to override half a property (at least, I always get confused about the exact rules) but it’s definitely odd to have camelCased names in C# code.Here’s an alternative implementation (no decorator class – it’s not clear how that was meant to help):