Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can one declare a static method within an abstract class, in Dart?

Tags:

In an abstract class, I wish to define static methods, but I'm having problems.

In this simple example

abstract class Main {   static String get name;   bool use( Element el ); }  class Sub extends Main {   static String get name => 'testme';   bool use( Element el ) => (el is Element); } 

I receive the error:

function body expected for method 'get:name' static String get name;

Is there a typo in the declaration, or are static methods incompatible with abstract classes?

like image 260
cc young Avatar asked Dec 23 '13 10:12

cc young


People also ask

Can we declare static method inside abstract class?

Declaring abstract method static If you declare a method in a class abstract to use it, you must override this method in the subclass. But, overriding is not possible with static methods. Therefore, an abstract method cannot be static.

Can we override static method in Dart?

Inheritance of static methods has little utility in Dart. Static methods cannot be overridden.

Can abstract class have static and final methods?

Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation. However, with abstract classes, you can declare fields that are not static and final, and define public, protected, and private concrete methods.

Does Dart have static classes?

The Dart static methodstatic methods are members of the class rather than the class instance in Dart. static methods can only use static variables and call the class's static method. To access the static method, we don't need to create a class instance. To make a method static in a class, we use the static keyword.


1 Answers

Dart doesn't inherit static methods to derived classes. So it makes no sense to create abstract static methods (without implementation).

If you want a static method in class Main you have to fully define it there and always call it like Main.name

== EDIT ==

I'm sure I read or heard some arguments from Gilad Bracha about it but can't find it now.

This behaviour is IMHO common mostly in statically typed languages (I don't know many dynamic languages). A static method is like a top level function where the class name just acts as a namespace. A static method has nothing to do with an instantiated object so inheritance is not applicable. In languages where static methods are 'inherited' this is just syntactic sugar. Dart likes to be more explicit here and to avoid confusion between instance methods and static methods (which actually are not methods but just functions because they don't act on an instance). This is not my primary domain, but hopefully may make some sense anyways ;-)

like image 55
Günter Zöchbauer Avatar answered Oct 09 '22 22:10

Günter Zöchbauer