Related to: Dart
Class 선언 및 인스턴스 생성
아래와 같이 class 선언하며 및 인스턴스 생성이 가능합니다.
’this’ 키워드는 C++과 같이 인스턴스 자기 자신을 가르키는 키워드입니다.
’final’로 정의한 멤버변수는 instance 생성 시 값을 할당할 수 있으며, 이후 변경할 수 없습니다.
class Idol{
final String name;
List<String> members = ['지수','제니','리사','로제'];
void sayHello(){
print('안녕하세요?')
}
Idol(string name){
this.name = name
}
}
var blackPink = Idol('블랙핑크');Const Constructor
‘const’ 키워드를 사용해서 인스턴스를 생성할 수 있습니다. 이 경우, 빌드 타임에 값을 알 수 있어야 합니다.
또한 기존 instance와는 별도로, 내부 값이 같다면 다른 같은 메모리를 가르키게 됩니다.
class Idol{
final String name;
final List<String> members;
const Idol(this.name, this.members);
}
var idol1 = const Idol('bp', ['a','b','c']);
var idol2 = const Idol('bp', ['a','b','c']);
print(idol1 == idol2); // true!!!Getter & Setter
아래와 같이 getter, setter를 정의할 수 있습니다.
class Idol{
String name;
List<String> members;
//some code
String get firstMember{
return this.members[0];
}
set firstMember(String name){
this.members[0]= name;
}
}Private 선언
‘_’를 이름 앞에 붙여서 Private로 선언할 수 있습니다.
_가 붙은 class , 함수, 변수는 다른 파일에서 참조할 경우 접근할 수 없습니다.
class _Idol{
//some code
}상속
‘extends’ 키워드를 사용하여 상속할 수 있습니다. 이 경우, ‘super’를 사용하여 부모의 constructor를 호출해야 합니다. 부모객체의 요소들을 ‘super.*’ 으로 참조할 수 있습니다.
class Idol{
Idol(int a, int b){
}
//some code
}
class BoyGroup extends Idol{
BoyGorup(int a, int b):super(a: a,b: b);
// some code
}Method Override
‘@override’를 Method 위에 적어 override 할 수 있습니다.
class TimesTwo{
final int number;
TimesTwo(this.number);
int calc(){
return number * 2;
}
}
class TimesFour extends TimesTwo{
TimesFour(int number) : super(number);
@override
int calc(){
return super.number * 4; // = return number = return this.number
}
}Static
‘static’ 키워드를 사용하여 정적 변수, 정적 메서드를 만들 수 있습니다.
class Employee{
static String building = 'A2';
static String PrintBuilding(){
return Employee.building;
}
}
print(Employee.building);
Employee.PrintBuilding();Interface
상속 시 extends 대신 ‘implements’ 키워드를 사용해서 interface처럼 구현을 강제할 수 있습니다.
또한 Interface로 사용할 class 앞에 ‘abstract’를 붙이면 해당 class는 인스턴스로 생성할 수 없고, 함수 body 구현도 생략할 수 있습니다.
abstract class IdolInterface{
String name;
void sayName();
IdolInterface(this.name);
}
class BoyGroup implements IdolInterface{
String name;
void sayName(){
return sayName;
};
BoyGroup(this.name);
}Generic
class 옆에 ‘
class Lecture<T> {
final T id;
final String name;
}
var lec = Lecture<int>();참조
[코드팩토리] [입문] Dart 언어 4시간만에 완전정복 - 인프런 | 강의
이 강의를 통해 Dart 언어를 배우면 Flutter를 시작할 수 있을 정도의 수준으로의 업그레이드가 가능합니다!
https://www.inflearn.com/course/dart-언어-입문/dashboard