0

I want to initialize super constructor in my dart. the code I want is like this:

class ChildClass extends ParentClass{ ChildClass(){ var startNumber = 4; var endNumber = 8; super(startNumber, endNumber); } } 

but, it will not work in dart code.

Alternative 1:

class ChildClass extends ParentClass{ ChildClass() : super(4,8); } 

the problem with alternative 1 is that it is not clean code. what is 4 and 8?

Alternative 2:

class ChildClass extends ParentClass{ int sNumber = 4; int eNumber = 8; ChildClass() : super(sNumber, eNumber); } 

the problem with alternative 2 is that the field sNumber and eNumber is redundant because we can use startNumber and endNumber from ParentClass if that field is public

Alternative 3:

class ChildClass extends ParentClass{ ChildClass({Int startNumber = 4, int endNumber = 8}) : super(startNumber, endNumber); } 

the problem with Alternative 3 is that we can change the value of parameter startNumber and endNumber

How can I call the super constructor while making clear the meaning of the values being passed?

1
  • Please do not use tags that explicitly say "DO NOT USE". Commented Apr 17, 2021 at 15:17

2 Answers 2

1

Ultimately your problem comes from wanting to make ParentClass's constructor parameters clearer. Therefore you ideally should make ParentClass's constructor take named parameters:

class ParentClass { int startNumber; int endNumber; ParentClass({required this.startNumber, required this.endNumber}); } class ChildClass { ChildClass() : super(startNumber: 4, endNumber: 8); } 

If you don't have control over ParentClass, then another alternative is to use named parameters with a private constructor in ChildClass instead:

class ChildClass { ChildClass() : this._internal(startNumber: 4, endNumber: 8); ChildClass._internal({required int startNumber, required int endNumber}) : super(startNumber, endNumber); } 
Sign up to request clarification or add additional context in comments.

Comments

1

Use alternative 2 and make the fields private and const:

class ChildClass extends ParentClass{ static const int _sNumber = 4; static const int _eNumber = 8; ChildClass() : super(_sNumber, _eNumber); } 

Comments