Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is @override annotation optional?

Tags:

dart

I understand definition of an @override annotation.

But, why is the usage of the annotation optional?

like image 628
Eternalcode Avatar asked Jul 12 '16 17:07

Eternalcode


People also ask

What is the use of @Override annotation in Java?

The @Override annotation tells the compiler that you are overriding that method which is previously defined in a super class. It helps the compiler verifying if in deed there is such a method defined in the super class or not.

What happens if you add an annotation to a method declaration?

What it expresses is that the method declaration on which it appears is intended to override a method declaration in a supertype. If you add the annotation to a method that doesn’t override another method in a supertype class, the compiler will generate an error.

What is the use of annotations in a supertype?

If you add the annotation to a method that doesn’t override another method in a supertype class, the compiler will generate an error. See, it’s useful mainly as documentation, albeit documentation that the compiler can enforce to a certain extent.

Why do I need to annotate the toString() method?

because you override a method. If that annotiation is missing and parent function would change then you might run into some problem. The annotation warns you, if the corresponding method doesn´t override the method any more. @KishanVaghela there is no need to, since it is showing the toString method, which initially comes from the Object.


2 Answers

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.
like image 153
Ng Ju Ping Avatar answered Sep 18 '22 11:09

Ng Ju Ping


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.

like image 24
lrn Avatar answered Sep 18 '22 11:09

lrn