객체지향
현재 글에서도 Kotlin에서 쓰던 것과 ‘어떻게 다르구나’라는 것을 한 번 나열하듯이 정리했다. 전체적으로 Java와 크게 다르지 않다.
클래스
class AppService {
}
void main() {
AppService kakaoTalk = new AppService() // new 생략 가능하다.
AppService faceBook = AppService()
}
Dart
복사
생성자(1)
class AppService {
String name;
List<String> functions;
AppService(String name, List<String> functions)
: this.name = name,
this.functions = functions;
}
Dart
복사
생성자를 위해 써줘야 할 글자수가 너무 많다. 아래 생성자(2)에서 더 단순하게 작성하는 방법을 설명한다.
생성자(2)
class AppService {
String name;
List<String> functions;
AppService(this.name, this.functions);
}
Dart
복사
생성자(1) 보다는 더 짧게 가능하다.
생성자(3)
class AppService {
String name;
List<String> functions;
AppService.sub(String name, List<String> functions)
: this.functions = values[0],
this.name = values[1];
}
void main() {
AppService instagram = AppService.sub(
'instagram',
[
'채팅', '피드', '검색', '설정', '좋아요', '댓글'
],
);
}
Dart
복사
생성자에 이름을 지정해 줄 수도 있다.
생성자(4)
class AppService {
String name;
List<String> functions;
const AppService(this.name, this.functions);
}
void main() {
AppService instagram = const AppService();
}
Dart
복사
생성자에 const 키워드도 붙여줄 수 있다. Flutter에서 이를 이용해 보다 효율적으로 처리할 수 있다.
Getter & Setter
String get firstFunction {
return this.functions[0];
}
set firstFunctions(String function) {
this.functions[0] = functions;
}
Dart
복사
Private
class _AppService{
}
Dart
복사
Dart에서는 앞에 언더바(_)를 붙여주게 되면 된다. 붙여주게 되면 같은 파일 안에서만 사용 가능하다.
상속
class MobileService extends AppService {
MobileService(String name, List<String> functions) : super(name: name, functions: functions);
}
Dart
복사
java와 동일하게 extends 키워드를 써준다.
Override
caclulate() {
return super.number * 4;
}
int Dart
복사
kotlin은 좌측에 override 키워드를 넣지만, dart는 java처럼 상단에 붙인다. override 키워드를 생략할 수는 있지만, 코드의 가독성과 규칙을 위해서 써주는걸 권장한다.
Static
class AppService {
static String? owner;
}
Dart
복사
Interface & Abstract
class ServiceBasicImpl implements ServiceBasic {
}
abstact class BasicService {
}
Dart
복사