继承
在dart中,和java一样,使用extends创建子类,使用super引用超类:
classTelevision{voidturnOn(){_illuminateDisplay();_activateIrSensor();}// ···}classSmartTelevisionextendsTelevision{voidturnOn(){super.turnOn();_bootNetworkInterface();_initializeMemory();_upgradeApps();}// ···}Overriding members
子类可以覆盖实例方法(包括操作符)、getter和setter。可以使用@override注解表示有意覆盖成员
classTelevision{// ···setcontrast(int value){// ···}}classSmartTelevisionextendsTelevision{@overridesetcontrast(num value){// ···}// ···}覆盖方法的声明必须在以下几个方面与它覆盖的方法匹配:
返回类型必须与被覆盖方法的返回类型相同(或为其子类型)。
形参类型必须与被覆盖方法的形参类型相同(或超类型)。在前面的例子中,智能电视的对比设置器将参数类型从int改为超类型num。
如果被覆盖的方法接受n个位置参数,那么覆盖的方法也必须接受n个位置参数。
泛型方法不能覆盖非泛型方法,非泛型方法也不能覆盖泛型方法。
noSuchMethod
当代码尝试使用不存在的方法或实例变量时,要检测或响应,你可以覆盖noSuchMethod():
classA{// Unless you override noSuchMethod, using a// non-existent member results in a NoSuchMethodError.@overridevoidnoSuchMethod(Invocation invocation){print('You tried to use a non-existent member: ''${invocation.memberName}',);}}“Dart 允许你调用不存在的方法,但必须有安全网:要么你明确告诉编译器’我不知道这是什么类型’(用 dynamic),要么你准备好’备用方案’(自定义 noSuchMethod())。”
如果不这么做,编译检查都过不了