클래스


<aside> 💡 클래스를 선언할 때, 클래스명은 대문자로 시작해야 한다. 클래스는 멤버 변수와 멤버 함수를 가질 수 있다.

</aside>

class ClassTest {
  String name = 'Han';

  void printName() {
    print('My name is ${this.name}!');
  }
}

void classTest() {
  ClassTest class1 = new ClassTest();
  class1.printName();
  class1.name = 'Haan';
  class1.printName();
}

클래스의 멤버 변수와 멤버 함수는 .을 사용하여 접근할 수 있다.

생성자


클래스는 생성자(Constructor)를 가질 수 있다. 생성자는 클래스와 동일한 이름으로 선언한다.

class ConstructorTest {
  String? name;
  String? age;

  ConstructorTest(String name, String age) {
    this.name = name;
    this.age = age;
  }

  void printName() {
    print('My name is ${this.name}(${this.age})!');
  }
}

void main() {
  ConstructorTest constructorTest = new ConstructorTest('Han', '29');
  constructorTest.printName();
}

final


클래스에서 final을 사용해서 인스턴스를 생성할 때, 상수를 설정할 수 있다.

class Test {
  final String? name;
  final String? color;

  Test({String? name, String? color})
      : this.name = name,
        this.color = color;

  void printName() {
    print('My name is ${this.name}(${this.color})!');
  }
}

void main() {
  Fruit test = new Fruit(name: 'Apple', color: 'Red');
  test.printName();

  test.name = 'Kiwi'; // << ERROR
}

Private 변수


Dart에서는 변수명 앞에 _를 추가함으로써, Private 변수를 생성할 수 있다. 클래스안에서만 Private 변수가 사용 가능한 다른 언어와는 달리, Dart에서는 클래스가 정의된 파일에서는 Private 변수에 접근할 수 있다.

class Test {
  String? _name;

  Test(String name) : this._name = name;

  void printName() {
    print('My name is ${this._name}!');
  }
}

void main() {
  Test test = new Test('1');
  test.printName();
  // Print Private variable
  // It's possibe because of same file.
  print(test._name);
}