如何在Dart中扩展Food类时排除num score属性?
问题解答
在Dart中,子类继承父类时会自动继承父类的所有公开成员(包括score属性),无法直接在子类中“移除”这个属性。不过可以通过以下几种方式实现类似需求:
1. 给父类score设置默认值
修改Food类的构造函数,为score添加默认值,这样子类构造时无需显式传递该参数:
class Food { String imgUrl; String desc; String name; String waitTime; num score; int price; int pq; int quantity; bool favourited; List<Variation> variations; Variation selectedVar; String about; bool highlight; // 为score设置默认值 Food( this.imgUrl, this.desc, this.name, this.pq, this.waitTime, this.price, this.quantity, this.variations, this.about, this.favourited, {this.score = 0, this.highlight = false} ); } // 子类构造时无需传入score class OrderedItem extends Food { Variation selectVar; OrderedItem( this.selectVar, super.imgUrl, super.desc, super.name, super.pq, super.waitTime, super.price, super.quantity, super.variations, super.about, super.favourited, {super.highlight = false} ); }
2. 使用组合代替继承
如果OrderedItem不需要Food的全部属性,更合理的方案是用组合模式替代继承,只保留需要的成员:
class OrderedItem { Variation selectVar; // 仅保留业务需要的属性 String imgUrl; String desc; String name; String waitTime; int price; int pq; int quantity; bool favourited; List<Variation> variations; Variation selectedVar; String about; bool highlight; OrderedItem( this.selectVar, this.imgUrl, this.desc, this.name, this.pq, this.waitTime, this.price, this.quantity, this.variations, this.about, this.favourited, {this.highlight = false} ); // 也可以持有Food实例,对外屏蔽score // final Food _food; // OrderedItem(this.selectVar, this._food); }
3. 子类中隐藏score(不推荐)
可以在子类中重写score,但这只是隐藏父类属性而非真正移除,容易引发逻辑混淆:
class OrderedItem extends Food { Variation selectVar; // 重写score,禁止外部访问 @override num get score => throw UnimplementedError('score is not available in OrderedItem'); @override set score(num value) => throw UnimplementedError('score is not available in OrderedItem'); OrderedItem( this.selectVar, super.imgUrl, super.desc, super.name, super.pq, super.waitTime, // 父类仍需初始化,传入默认值 0, super.price, super.quantity, super.variations, super.about, super.favourited, {super.highlight = false} ); }
总结:最推荐的方案是修改父类给score添加默认值,或使用组合模式。继承的本质是复用父类全部成员,无法直接移除父类已有的属性。
内容的提问来源于stack exchange,提问作者shimomaru
相关产品推荐
相关产品推荐

