Dart 객체 지향 프로그래밍 OOP
출처 : 코드팩토리 객체지향 프로그래밍
생성자, Getter and Setter, Private 속성, 상속 Inheritance, Override, static, Interface, Generic
클래스 - 기능을 모아둔 것
인스턴스 - 클래스로 만든 것, 무한히 생성 가능
## 생성자 constructor
@ 클래스 생성
void main(){
Idol blackPink = const Idol( '블랙핑크',['제니','지수','리사','로제']); // 클래스로 인스턴스 생성 , const로 선언할 수 있는 파라미터만 있는 경우에는 const 인스턴스 생성 가능
print(blackPink.name);
blackPink.sayHello();
Idol bts = Idol('BTS',['진','정국']); }
class Idol { // Idol class 생성 - name 변수, members 변수 , sayHello 함수, introduce 함수
final String name;
final List<String> members; // 변경할 수 없도록 하는 습관을 들여야함
@ 생성자 // Idol(); - 가장 기본적인 생성자
const Idol(String name, List<String> members) : this.name = name, this.members = members; //this는 현재 클래스를 의미 , const constructor로 생성하면 const 인스턴스를 생성 가능
void sayHello(){
print('안녕하세요 ${this.name}입니다.');
}
void introduce(){
print('저희 멤버는 ${this.members}가 있습니다');
}
}
@ 생성자 간결하게 작성
Idol(this.name, this.members);
@ named constructor
Idol.fromList(List values)
: this.members = values[0],
this.name = values[1];
Idol bts = Idol.fromList([['진','정국'],'bts']);
@ 매개변수 값이 모두 같은 인스턴스 2개를 생성해도 그 두개는 같지 않은 것
but 매개변수 값이 모두 같은 const 인스턴스 2개를 생성하면 두 개는 같은 것
## Getter and Setter( Getter - 데이터를 가져올때/Setter - 데이터를 설정할 때)
@ Getter 선언 (클래스 안에) 반환타입 get 이름 {}
String get firstMember{
return this.members[0];
}
(main 함수 안에서)
print(blackPink.firstMember)
@Setter (클래스 내에) 값을 안바꾸려고 하는 현대에 잘 안쓰는 기능
set firstMember(String name){ // 무조건 한개의 파라미터만 가능
this.members[0] = name; // 값 변경
}
(main 함수 내에)
blackPink.firstMember = '아이언맨';
@ 함수와의 차이 : 기능적으로는 거의 없음. 간단하게 데이터를 가공할 때 사용
## Private 변수 - 파일 밖에서 변수를 사용할 수 없도록 만들 때 , 함수, 변수, 클래스 다 적용 가능
class _Idol {
클래스 내에도 다 _ 처리하기
}
## 상속(Inheritance) - 상속을 받으면 부모 클래스의 모든 속성을 자식 클래스가 부여받는다.
class Idol{
String name;
int numberCount;
Idol({required this.name, required this.memberCount,})
void sayName(){ print('저는 ${this.name}입니다.');}
void sayMembersCount(){ print('${this.name}은 ${this.numberCount}명의 멤버가 있습니다.');}
}
@ 부모 클래스를 지정하는 건 super
class BoyGroup extends Idol {
BoyGroup{
String name, int membersCount,
} : super(name : name, membersCount: membersCount,); // 부모 클래스에 파라미터 전달
}
void main(){
BoyGroup bts = BoyGroup('BTS',7);
bts.sayMembersCount(); // 부모클래스에 상속받아서 함수 사용 가능
}
@ 자식클래스에서 부모클래스로 상속하는 건 없음
@ 자식클래스로 생성한 인스턴스는 부모 클래스와 같은 타입 인가? print(bts is BoyGroup); => true
## Override
@메소드 method - 클래스 내부에 있는 함수
@메소드 override 덮어쓴다(우선시 하다)
void main(){
TimeTwo tt = TimesTwo(2);
print(tt.calculate());
TimeFour tf = TimeFour(2);
print(tt.calculate());
}
class TimesTwo {
final int number;
TimesTwo{this.number,};
int calculate(){
return number*2; // number라는 또다른 변수가 calculate 함수 안에 선언되지 않는다면 this.number라고 안써도 됨}
}
class TimesFour extends TimesTwo{
TimesFour{int number,} : super(number);
@override // 골뱅이 꼭 넣어줘야함
int calculate(){ // 부모 클래스에 있는 함수 덮어쓰기, 추가적인 로직을 적어줄 수 있다.
return super.number*4; // this.number로도 가능 같은 값이어서 super.도 생략 가능 number 변수가 하나여서
// return super.calculate()*2; 도 같은 기능
}
}
## Static - 인스턴에 귀속되지 않고 class에 귀속된다.
void main(){
Employee seulgi = Employee('슬기');
Employee chorong = Employee('초롱');
seulgi.name = '다'; // 인스턴스에 귀속된다.
Employee.building = '삼성'; // 슬기와 초롱 모두 빌딩값이 바뀜 => 클래스에 귀속된다.
Employee.printBuilding(); //static 함수 호출 가능
}
class Employee {
static String? building;
final String name;
Employee(this.name,);
static void printBuilding(){
print('저희는 ${building}에서 근무중입니다.');
}
}
## Interface - 클래스를 만들 때 인터페이스 사용, 특정 구조를 강제 - 다른 개발자들과 소통없이 필수적으로 넣어야하는 기능을 알릴 수 있음.
@ 클래스로 선언
class IdolInterface {
String name;
IdolInterface(this.name);
void sayName(){};
}
class BoyGroup implements IdolInterface{ // 인터페이스의 모든 시그니처를 맞춰주어야함, implements로 사용
String name;
IdolInterface(this.name);
void sayName(){
print('제 이름은 ${name}입니다');}
}
@ abstract - 실수로 인터페이스를 인스턴스화 시키는 것을 방지
abstract class IdolInterface{ // IdolInterface를 인스턴스화 하면 에러
String name;
IdolInterface(this.name);
void sayName(); // 함수의 바디를 지워도 됨.
}
## Generic - 타입을 외부에서 받을 때 사용
void main(){
Lecture<String> lecture1 = Lecture('123', 'lecture1');
}
class Lecture<T> { // 여러개 받을 때는 <T, X> 이름은 아무거나 가능
final T id; // id의 데이터 타입을 변수처럼 외부에서 받을 수 있음
final String name;
Lecture{this.id, this.name};
}
@ 모든 클래스의 최상위 부모 클래스는 오브젝트이다. 그래서 객체지향 프로그래밍 OOP Object Oriented Programming