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

安稳与你 提交于 2020-04-12 20:59:07

问题


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?


回答1:


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 ;-)




回答2:


Looks like you are trying to 'override' a static method. I'm not sure what you are trying to achieve there. I'm not aware of any OO languages that support that (and not sure how they could).

A similar question in Java might help clarify Polymorphism and Static Methods

Note also that it is considered bad practice to refer to statics from an instance of the class in Java (and other OO languages). Interestingly I noticed Dart does not let you do this so is in effect removing this bad practice entirely.

So you couldn't even fool yourself into thinking it would behave polymorphically in Dart because you can't call the static from the instance.



来源:https://stackoverflow.com/questions/20741737/can-one-declare-a-static-method-within-an-abstract-class-in-dart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!