我想实现的装饰图案,在这里我specfication:装饰模式,编译器不允许类型传播
public abstract class Menu{ //propagate the type
}
而且
public class Sandwich extends Menu{ // Concrete class which is a Menu
}
而且
public abstract class Extra extends Menu{
Menu menu;
public Extra(Menu menu){ // the constructor takes a Menu type
this.menu=menu;
}
}
的问题是为什么编译器不允许这样做:
public class Test {
Menu sand1 = new Sandwich();
sand1 = new Extra(sand1); //It's fine for the compiler
Sandwich sand = new Sandwich();
sand = new Extra (sand);// Compiler cries here !!
}
三明治IS-A Menu
通过inheritence,Extra
的构造函数需要Menu
所以为什么编译器不开心?
编译器消息:Type mismatch: cannot convert from Extra to Sandwich
感谢您的澄清。
'Extra'不是'Sandwich' ...编译器说什么_exactly_? –
@SotiriosDelimanolis我添加了编译信息 – akuma8
好吧,你去了,我不明白你的困惑。问题在错误消息中详细说明。 –