Thuta Learning
ရှာဖွေရန်
IntermediateProgrammingbeginner

Constructors

စိတ်လျှော့ပါ။ ဒီခန်းကို စာအုပ်လိုမဟုတ်ဘဲ စကားပြောသလိုပဲ၊ နားလည်လွယ်အောင် ရှင်းပါမယ်။

Constructor သည် class က object အသစ်ဖန်တီးတဲ့အချိန် အလုပ်လုပ်တဲ့ special method ဖြစ်ပါတယ်။ Dart မှာ short-form constructor, named constructor, initializer list စတဲ့ရေးနည်းတွေရှိပါတယ်။

dart
class Point {
  final double x;
  final double y;

  Point(this.x, this.y);

  Point.origin()
      : x = 0,
        y = 0;

  Point.vertical(double yValue)
      : x = 0,
        y = yValue;
}

void main() {
  final p1 = Point(2, 3);
  final p2 = Point.origin();
  final p3 = Point.vertical(10);

  print('p1: ${p1.x}, ${p1.y}');
  print('p2: ${p2.x}, ${p2.y}');
  print('p3: ${p3.x}, ${p3.y}');
}

Point(this.x, this.y) က normal constructor ပါ။ Point.origin() နဲ့ Point.vertical() က named constructors ဖြစ်ပြီး object ဖန်တီးတဲ့ purpose ကိုနာမည်နဲ့ရှင်းပြပေးပါတယ်။

You should see
p1: 2.0, 3.0 p2: 0.0, 0.0 p3: 0.0, 10.0

ဒီနေရာမှာ လူအများမှားတတ်တယ်

  • Named constructor သုံးတဲ့အခါ class name နောက်မှာ dot နဲ့ constructor name ခေါ်ရပါမယ်။ ဥပမာ Point.origin() ။
Constructors | Thuta Learning