devlog_zz

[Dart] 4. 조건문 반복문, 클래스, 생성자 본문

Front End/Flutter

[Dart] 4. 조건문 반복문, 클래스, 생성자

YJ_SW 2022. 5. 20. 14:05
728x90

조건문 반복문, 클래스, 생성자

assert(조건식);

조건식이 거짓이면 에러가 발생한다.

debug mode에서만 동작

클래스

클래스는 멤버를 가진다.

멤버는 멤버함수( 메서드 ), 멤버변수( 인스턴스 변수)로 구성

클래스를 사용하려면 객체를 생성해야 함

객체 생성 == 클래스가 메모리에 올라간다 == 인스턴스화

메모리에 클래스가 할당되어 인스턴스가 된 것을 객체라고 함

function : 클래스 외부에서 하나의 기능을 수행

method : 클래스 내부

멤버변수는 객체가 생성되면 인스턴스 변수라고 함

class Person {
	String name;
	
	getName() {
		return name;	
	}
}

var student = Person(); // new Person() 해도 동일

생성자

클래스가 인스턴스화 될 때, 즉 객체가 생성될 때 호출됨

class Person {
	**Person() { // 생성자
	}**
}

생성자를 선언하지 않으면 기본 생성자가 자동으로 제공됨

상속

class Person {
	Person() { 
		print('This is Person Constructor !');

	}
}

class Student extends Person {
}

main(){
	var student = Student();
}

// 결과
This is Person Constructor! - 1

Person 부모, Student 자식

자식 클래스엔 생성자가 없을 때 기본 생성자는 부모 클래스의 기본생성자를 호출

class Person {
	Person() { 
		print('This is Person Constructor !');

	}
}

class Student extends Person {
	Student() {
		print('This is Student Contsructor !');
	}
}

main(){
	var student = Student();
}

// 결과
This is Person Constructor !
This is Student Contsructor !

부모 클래스의 기본 생성자 호출 후 자식 클래스의 기본 생성자 호출

2. 이름있는 생성자

class Person {
	Person() { 
		print('This is Person Constructor !');
	}
	Person.init() { 
		print('This is Person.init Constructor !');

	}
}

main(){
	var init = Person.init();

}

이름 없는 생성자는 단 하나만 가질 수 있음

이름 있는 생성자를 선언하면 기본 생성자는 생략할 수 없다.

3. 초기화 리스트

생성자의 구현부가 실행되기 전에 인스턴스 변수를 초기화 할 수 있다.

초기화 리스트는 생성자 옆에 : 으로 선언 가능

Person() : name = 'Kim'{
}

4. 리다이렉트 생성자

초기화 리스트를 응영하여 리다이렉팅을 위한 생성자

생성자 본체가 비어있고 메인 생성자에게 위임하는 역할

 

 

출처 : https://brunch.co.kr/brunchbook/dartforflutter 스터디하며 정리한 글입니다. 감사합니다.

728x90

'Front End > Flutter' 카테고리의 다른 글

[Dart] 6. 비동기 프로그래밍  (0) 2022.05.20
[Dart] 5. 상속, 접근 지정자, Getter Setter  (0) 2022.05.20
[Dart] 3. 함수, 연산자  (0) 2022.05.20
[Dart] 2. Dart 문법 및 특징  (0) 2022.05.20
[Dart] 1. dart 기초 및 소개  (0) 2022.05.20
Comments