I get the following error
The 'super' keyword can't be used in an extension because an extension doesn't have a superclass.
With this code,
class Animal {
final String name;
Animal({required this.name});
void jump() {
print("Jumping");
}
}
class Dog extends Animal {
final String breed;
Dog({required this.breed, required super.name});
}
extension DogExtension on Dog {
void jump() {
super.jump();
print("and Waving Tail");
}
}
I can’t simply override the method in the class Dog directly instead of using an extension because class Dog
is auto generated by a code generator.
Also, I don’t want to simply rename jump
in the extension to jumpDog
, because Dog will have it’s own inherited class, I’d like to use jump
for all.
2
Answers
Answer to the direct question, you can’t use
super
keyword inside extension. Extension is not really a class hence not really a sub-class to be able to use the super keyword. It’s more like a additional part you can fit on to a class.Secondly, even if you call the
jump
method inside the extension withthis
keyword as following code, it’ll only call the jump method derived from the super class ofDog
.Which primarily means the jump() method inside the DogExtension is never called.
If you’re seriously willing to override the Dog class’s
jump
method you should try considering mixins.Now the
dog.jump()
call will invoke the overridden method fromDogMixin
.Hope this helps.
you can’t use extension to override other class : https://github.com/dart-lang/language/issues/1127
if you no macros, no code gen, you can’t do this case ,you only can do is :