void main() {
//实例化
ShoppingCart sc = ShoppingCart("小米", "T3482");
//List集合赋值
sc.books = [Item('苹果', 10.2), Item('鸭梨', 8.5)];
//调用打印方法
sc.printInfo();
}
class Meta {
double price;
String name;
//构造函数+赋值属性
Meta(this.name, this.price);
}
class Item extends Meta {
//构造函数
Item(name, price) : super(name, price);
//重载构造函数
Item.n(name) : super(name, 0.111);
// 重载了 + 运算符,合并商品为套餐商品
Item operator +(Item item) => Item(name + item.name, price + item.price);
}
//抽象类
abstract class PrintHelper {
void printInfo() => print(getInfo());
getInfo();
}
//多继承的时候,可以使用“混入”(Mixin)关键字with
class ShoppingCart extends Meta with PrintHelper {
String name;
DateTime date;
String code;
List<Item> books;
ShoppingCart(this.name, this.code)
: date = DateTime.now(),
super(name, 0.0);
double get price => books.reduce((value, element) => value + element).price;
getInfo() => '''
购物车信息:
-----------------------
用户名:$name
优惠券:$code
总价:$price
日期:${date.toString()}
-----------------------
''';
}
运行后:
购物车信息:
-----------------------
用户名:小米
优惠券:T3482
总价:18.7
日期:2019-07-21 15:07:29.390174
-----------------------
网友评论