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.
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; otherwise, you would not have a chance to initialize it, which is required because it is final in the superclass.