why abstract class instantiation isn't runtime error in dart?

为君一笑 提交于 2021-02-09 05:50:09

问题


In many languages if you try to instantiate abstract class you get compile time error. In Dart however, you get warning while compiling and a runtime exception AbstractClassInstantiationError.

Why is that? Can someone provide an example, where it's reasonable to compile such code?


回答1:


Dart tries to allow you to run your program while you are developing it. That is why many things that are compile time errors in other languages are compile-time warnings and runtime errors in Dart. This includes "x is Foo" where Foo doesn't exist, type-annotating with a non-existing types, and calling constructors of partial (abstract) classes.

In short: because it's not a problem that prevents the program from being compiled (unlike a syntax error that might mean the rest of the file is interpreted wrongly), so there is no reason to stop you from running the code. Only if you hit the branch that actually depends on the problem will your program be stopped.




回答2:


It appears that the answer is factory constructor in abstract class:

abstract class Foo {
  factory Foo() { // make Foo appear to be instantiable
    return new Bar();
  }
  some(); // some abstract method
  Foo.name() {} just a named constructor
}

class Bar extends Foo {
  Bar():super.name(); // call named super constructor
  some() {} // implement abstract method
}

main() {
  print(new Foo()); // "instantiate" abstract Foo
}

Output:

Instance of 'Bar'



回答3:


Asking 'where it's reasonable to compile such code?' in Dart isn't very meaningful because Dart is an interpreted language - there is no compilation stage. Dart editors will issue warnings if they think you are making a type error as they analyse your code on the fly.

Factory constructors can be used to provide a 'default' concrete implementation of an abstract class as you have done in your example. This is used quite widely in Dart. For instance, if you create a new Map object you actually get a LinkedHashMap object - see this question and answer.

In your example your are not instantiating an instance of Foo ('new Foo' does not appear anywhere), you are instantiating a `Bar'. This is because when a factory constructor is called a new instance of its class is not automatically instantiated.



来源:https://stackoverflow.com/questions/27051164/why-abstract-class-instantiation-isnt-runtime-error-in-dart

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