공부

[Dart] 2. OOP

avocado8 2024. 3. 20. 17:19

 

 

클래스 선언

class 클래스명 {

  //final 키워드: 한번 선언되면 값 바꿀 수 없게

  final String name;

  final List<String>members;

  //constructor

  //const constructor 선언 가능 / const로 선언시 인스턴스에서도 const constructor 사용

  //내용이 같을 경우 const로 선언시 같은 인스턴스가 됨

  const 클래스명(String name, List<String>members) : this.name = name, this.members = members;

  //methods

  ....

}

* 모든 클래스는 Object 클래스를 상속받음

 

인스턴스 선언

클래스명 Cado = 클래스명('name', ['cado','nana'],);

 

constructor

클래스명(this.name, this.members);

간결하게 써도됨

 

named constructor

클래스명.fromList(List values) : this.members = values[0], this.name = values[1];

//클래스명.fromList([...], 'name') -> 기본 constructor과 동일하게 동작

 

getter / setter

데이터 가져올때 / 설정할때

//getter

get firstMem { return this.members[0] }

 

//setter

//parameter은 무조건 1개

set firstMem(String name) { this.members[0] = name; }

 

private 속성

class _Idol { ... }

언더스코어(_) 붙여준 것은 현재 파일에서만 사용가능. 외부파일에서 사용불가

 

상속

부모클래스의 모든 속성을 자식클래스가 받음

class Friends {
  String name;
  int memsCount;
  Friends({
    required this.name,
    required this.memsCount,
  });
  void sayName() {
    print("이름은 ${this.name}");
  }

  void sayMemsount() {
    print("${this.memsCount}명");
  }
}

class Whale extends Friends {
  Whale(
    String name,
    int memsCount,
  ) : super(
          name: name,
          memsCount: memsCount,
        );
}

부모클래스를 지칭하는 단어는 super

 

static

static은 인스턴스가 아닌 클래스에 귀속됨

constructor로 선언하지 않아도 클래스자체에서 접근가능

클래스 자체에서 접근해 선언시 모든 인스턴스에 적용됨

 

interface

형식을 지켜서 클래스를 만들 때

특정 구조를 강제함

class 키워드로 선언, implements로 받음

abstrcat class로 선언하여 인스턴스로 만들어지는 것을 막을 수 있음 (함수 body도 생략 가능)

abstract class IdolInterface {
  String name;
  IdolInterface(this.name);
  void sayName()
}

class BoyGroup implements IdolInterface {
  String name;
  BoyGroup(this.name);
  void sayName() {}
}

 

generic

타입을 외부에서 받을 때 사용

void main() {
  Lecture<String> lec1 = Lecture('123', 'lec1',);
  lec1.printIdType(); //String
  Lecture<int> lec2 = Lecture(123, 'lec2');
  lec2.printIdType(); //int
}

class Lecture<T> {
  final T id;
  final String name;
  Lecture(this.id, this.name);
  void printIdType(){
    print(id.runtimeType);
  }
}

 

외부에서 지정한 타입으로 constructor에 적용

 

'공부' 카테고리의 다른 글

[React] Styled Component에서 props로 공통 스타일 정의하기  (0) 2024.08.09
Vite 환경변수 설정하기  (1) 2024.06.26
[Dart] 1. 기본  (1) 2024.03.20
[Flutter] Pomodoro app  (0) 2024.03.12
리덕스 기초  (0) 2024.02.06