Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to declare a method as final in a class in Dart?

In Java one can declare a method within a class to prevent subclasses from overriding it.

For example:

class Foo {

   final void bar() {
     // some code here.
   }

}

Is there a similar construction in Dart?

like image 308
Teakwood J Overclutch Avatar asked Sep 21 '20 00:09

Teakwood J Overclutch


People also ask

Can a class be final in Dart?

Dart has a very simple definition of what is final : a variable in dart can only be set once, id est: is immutable. Final and const If you never intend to change a variable, use final or const, either instead of var or in addition to a type.

Does Dart support method overriding?

Dart did not support overloading originally because it was a much more dynamic language where the declared types did not have any semantic effect. That made it impossible to use static type based overload resolution.

What does @override do in Dart?

The annotation @override marks an instance member as overriding a superclass member with the same name. The annotation applies to instance methods, getters and setters, and to instance fields, where it means that the implicit getter and setter of the field is marked as overriding, but the field itself is not.


2 Answers

package:meta provides a @nonVirtual annotation to disallow overriding methods and a @sealed annotation to disallow derived classes entirely.

Note that these annotations just provides hints to dartanalyzer. They won't actually prevent anything from violating the annotations, and they instead will cause warnings to be printed when analysis is performed.

like image 80
jamesdlin Avatar answered Nov 15 '22 10:11

jamesdlin


Yes, code for Irn & Jamesdlin answer:

import 'package:meta/meta.dart';

class Foo { 
   @nonVirtual 
   void bar() {
     print("bar from Foo!");
   } 
}

class SubFoo extends Foo {
  @override
   void bar()  {
      print("bar from SubFoo");
   }
} 

And you get the warning from Analyzer like this:

The member 'bar' is declared non-virtual in 'Foo' and can't be overridden in subclasses.dart(invalid_override_of_non_virtual_member)

like image 43
searching9x Avatar answered Nov 15 '22 09:11

searching9x