简体   繁体   English

在 Dart 中扩展抽象类是否会给子类另一个构造函数

[英]Does extending an abstract class in Dart give the subclass another constructor

I created an abstract class with final variables, because of that I needed to create a constructor inside of it to instantiate the variables.我创建了一个带有最终变量的抽象类,因为我需要在其中创建一个构造函数来实例化变量。 Will this constructor be added to all classes that extend the abstract class?这个构造函数会被添加到所有扩展抽象类的类中吗? I am thinking not so because some of my subclasses will have additional final variables that would need to be instantiated.我不这么认为,因为我的一些子类将有额外的最终变量需要实例化。 If this is the case what role does the abstract class' constructor play?如果是这种情况,抽象类的构造函数起什么作用?

For reference:以供参考:

abstract class SuperClass {
  final String item
  SuperClass(item)
  : item = item;
}

class SubClass { 
  final String item
  final String item2
  SubClass(item, item2)
  : item = item,
  item2 = item2;
}

Is extending the best option in this case and if so will the super class' constructor be seen?在这种情况下是否扩展最佳选择,如果是,是否会看到超类的构造函数?

The abstract class in your case is just a normal class because it does not have any abstract properties/methods.您的情况下的抽象类只是一个普通类,因为它没有任何抽象属性/方法。 The only thing that you can not do is create an instance of that abstract class.您唯一不能做的就是创建该抽象类的实例。 Extending the SuperClass makes sense because you will no longer need to define fields that are declared in the super class, like the "item" field.扩展 SuperClass 是有意义的,因为您将不再需要定义在超类中声明的字段,如“item”字段。

In order to benefit from it, you need to write your subclass slightly different:为了从中受益,您需要编写稍微不同的子类:

abstract class SuperClass {
  final String item;
  SuperClass(this.item);
}

class SubClass extends SuperClass {
  final String item2;
  SubClass(String item, this.item2) : super(item);
}

Please note that the subclass constructor calls the superclass' constructor and passes the item value to it.请注意,子类构造函数调用超类的构造函数并将项目值传递给它。 You still have to declare the item value in your subclass' constructor though;不过,您仍然必须在子类的构造函数中声明 item 值; otherwise, you would not have a chance to initialize it, which is required because it is final in the superclass.否则,您将没有机会初始化它,这是必需的,因为它在超类中是最终的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM