Up to what I researched, in Dart you gotta call super outside the function body of the constructor.
Suppose this situation:
/// Unmodifiable given class
class Figure{
final int sides;
const Figure(this.sides);
}
/// Own class
class Shape extends Figure{
Shape(Form form){
if(form is Square) super(4);
else if(form is Triangle) super(3);
}
}
That throws analysis errors (the superclass doesn't have 0 parameters constructor & the expression super(3) doesn't evaluate to a function, so it can't be invoked). How could I achieve the desidered functionality of the example?
Super Keyword in Dart: In Dart, super keyword is used to refer immediate parent class object. It is used to call properties and methods of the superclass. It does not call the method, whereas when we create an instance of subclass than that of the parent class is created implicitly so super keyword calls that instance.
_(); is a named constructor (another examples might be the copy constructor on some objects in the Flutter framework: ThemeData. copy(...); ). In dart, if the leading character is an underscore, then the function/constructor is private to the library.
Child_class_constructor() :super() { ... } Implicit super: In this case, the parent class is called implicitly, when there is object creation of child class. Here we don't make use of the super constructor but when the child class constructor is invoked then it calls default parent class constructor.
In Dart for calling the super constructor the initializer list is used.
class Shape extends Figure{
Shape(Form form) : super(form is Square ? 4 : form is Triangle ? 3 : null);
}
if you need to execute statements you can add a factory constructor that forwards to a (private) regular constructor like
class Shape extends Figure{
factory Shape(Form form) {
if (form is Square) return new Shape._(4);
else if(form is Triangle) return new Shape._(3);
}
Shape._(int sides) : super(sides)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With