如何使用工厂构造函数扩展抽象类? [英] How to extend an abstract class with factory constructor?

查看:95
本文介绍了如何使用工厂构造函数扩展抽象类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

情况如下:

abstract class A {
  void doSomething() => print('Do something..');
}

class B implements A {
  @override
  void doSomething() => print('Do something already..');
}

class C extends A {
}



<我有一个抽象类A。
B类实现了A。因此,它重写了doSomething()方法。 C类扩展了A。

I have an abstract class A. Class B implements A. Therefore it overrides doSomething() method. Class C extends A.

一切正常,直到我向A类添加工厂构造函数为止:

Everything works fine, until I'm adding factory constructor to class A:

abstract class A {
  factory A() => new B();

  void doSomething() => print('Do something..');
}

这会导致我的IDE(IntelliJ IDEA)中出现错误:

This leads to an error in my IDE (IntelliJ IDEA):


期望生成生成器,但工厂找到了

The generative constructor expected, but factory found

我的第一个想法是为类C创建构造函数,我将为A调用工厂构造函数。

My first idea was to create constructor for class C where I would call factory constructor for A. Is it possible to do?

当我尝试扩展时,我遇到了同样的问题异常类。它还有一个工厂构造函数:

I got the same problem when I try to extend Exception class. It also has a factory constructor:

abstract class Exception {
  factory Exception([var message]) => new _ExceptionImplementation(message);
}

这就是为什么要创建自定义异常的原因,我必须实现Exception类而不是扩展

Thats why to create my custom exception I have to implement Exception class instead of extending it and it really confuses me.

我还想澄清一个术语问题。
我可以说从B类的角度来看,A是一个接口,所以B在实现接口A。
但是,从C类的角度来看,A是一个抽象类,所以C是扩展这些抽象类A。这些语句正确吗?

I also would like to clarify one terminology question. Can I say that from point of view of B class, A is an interface, so B is implementing interface A. However, from point of view of C class, A is an abstract class so C is extending abstract class A. Are these statements correct?

谢谢。

Dmitry。

推荐答案

如果类没有构造函数,则会隐式添加生成的构造函数。如果类具有显式构造函数,则不添加生成构造函数。
您有两个选择。

If a class has no constructor a generative constructor is implicitly added. If a class has an explicit constructor no generative constructor is added. You have two options.


  • 将工厂构造函数命名为工厂构造函数并添加普通的构造函数

abstract class A {
  void doSomething() => print('Do something..');
  factory A.name() => new B();
  A();
}




  • 或使普通构造函数命名并调用它明确地来自扩展类

  • abstract class A {
      void doSomething() => print('Do something..');
      factory A() => new B();
      A.protected();
    }
    
    class C extends A {
      C() : super.protected();
    }
    

    尝试在 DartPad

    您的陈述正确。如果您实现一个类,则它充当接口,而如果扩展它,则其充当基类。

    Your statement is right. If you implement a class it acts as an interface and if you extend it it acts as a base class.

    这篇关于如何使用工厂构造函数扩展抽象类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆