Question

What Is The Purpose of @override used in Flutter?

In the flutter documentation the keyword @override is used a lot in classes. I tried to search for the meaning but still can't understand. What is the purpose of this @override Keyword.

Note: I come from a JavaScript background.

 46  45241  46
1 Jan 1970

Solution

 58

@override just points out that the function is also defined in an ancestor class, but is being redefined to do something else in the current class. It's also used to annotate the implementation of an abstract method. It is optional to use but recommended as it improves readability.

The annotation @override marks an instance member as overriding a superclass member with the same name.

https://api.dartlang.org/stable/1.24.3/dart-core/override-constant.html

JavaScript also supports @override as an annotation, but it has to be in a comment. http://usejsdoc.org/tags-override.html.

2018-07-07

Solution

 9

According to docs
The annotation @override marks an instance member as overriding a superclass member with the same name.

Example

class A {
  void foo() {
    print("Class A");
  }
}

class B extends A {}

class C extends A {
  @override foo() {
    print("Class C");
  }
}

void main() {
  A a = A();
  B b = B();
  C c = C();
  a.foo();
  b.foo();
  c.foo();
}

The Output is:

Class A
Class A
Class C

What happening is B extends A and hence inherits all the methods of A. Hence when b.foo() is called it calls method from its parent class.

But in C it has foo with override keyword which means it will override foo declaration in its parent class.

2021-12-27