Eternalcode
Eternalcode

Reputation: 2412

Why is @override annotation optional?

I understand definition of an @override annotation.

But, why is the usage of the annotation optional?

Upvotes: 10

Views: 2567

Answers (4)

Ng Ju Ping
Ng Ju Ping

Reputation: 327

Because the name of the method is looked up in the inheritance chain: for example, let's look at this inheritance chain:

A
|
B
|
C

if we create an instance using class C and invoke a method test(), then the definition of test is first looked in the body of class C, then class B, then class A. Thus, the overriding effect is automatically implied. The effect is similar to what observed in C++, and for a detailed read please check out this link:
https://isocpp.org/wiki/faq/strange-inheritance#hiding-rule


The reason of the existence of the annotation is clearly stated above by Abaddon666.

Upvotes: 2

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657721

You can enable a linter rule to enforce it

by adding an .analysis_options file to your project besides the pubspec.yaml file with this content

linter:
  rules:
    - annotate_overrides

Upvotes: 6

lrn
lrn

Reputation: 71743

The annotation wasn't made part of the language because the language designers didn't want to enforce its use.

It has been added as an optional annotation for people who want the feature, but it's only recognized by the analyzer tool, it's not actually part of the language.

Upvotes: 7

Abaddon666
Abaddon666

Reputation: 1623

From the documentation:

The intent of the @override notation is to catch situations where a superclass renames a member, and an independent subclass which used to override the member, could silently continue working using the superclass implementation.

You might want to name your method equal to the super class without explicitely overriding it. This is allowed as it does not break any constraints. Basically you can name your methods whatever you want.

@Override only enforces, that one of your parents has to have a method with the same signature.

Upvotes: 9

Related Questions