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?
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.
Inheritance of static methods has little utility in Dart. Static methods cannot be overridden.
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.
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.
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 ;-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With