Dart 2 객체지향 프로그래밍

2022. 10. 2. 20:33프로그래밍 언어/Flutter

목차
1. class 
   1) Getter , Setter
2. 상속 
   1) Override
   2) static
3. Interface
4. generic 
5. Object

 

1. class 

void main() {
  Idol blackPink = Idol('블랙핑크', ['지수', '로제', '리사', '제니']); // new 안써도 됨
  print(blackPink.name);   //블랙핑크
  print(blackPink.members); // [지수, 로제, 리사, 제니]
  blackPink.sayHello(); // 안녕하세요. 블랙핑크입니다.
  blackPink.introduce(); // 저희 멤버는 [지수, 로제, 리사, 제니]가 있습니다.

  Idol bts = Idol('bts', ['RM','뷔']); 
  print(bts.name);  //bts
  print(bts.members); // [RM, 뷔]
  bts.sayHello(); // 안녕하세요. bts입니다.
  bts.introduce(); // 저희 멤버는 [RM, 뷔]가 있습니다.
 
}

// Idol class
// name(이름) -변수
// members (멤버들) - 변수
// sayHello(인사) -함수
// introduce(멤버소개) - 함수
class Idol {
  String name;
  List<String> members;

  Idol(String name, List<String> members)
      : this.name = name,
        this.members = members;
  void sayHello(){
    print('안녕하세요. ${this.name}입니다.');
  }
   void introduce(){
    print('저희 멤버는 ${this.members}가 있습니다.');
  }
}

아래 부분을 

  Idol(String name, List<String> members)
      : this.name = name,
        this.members = members;

아래처럼 축약 가능하다. 

  Idol(this.name,this.members);

클래스의 변수를 final 로 선언하는 습관을 들여야 한다. 

  why? : 버그 방지가 편함. 

생성자 선언시 const 로 선언하는 습관을 들여야한다. 

  why? : 효율을 올려주는데 좋음 

    why? : const 로 생성한 인스턴스는 값이 동일하면 같은 걸 바라봄 

class Idol {
  final String name;
  final List<String> members;

  const Idol(this.name,this.members);
 }

const 로 선언시 값이 같으면 true

Idol blackPink = const Idol('블랙핑크', ['지수', '로제', '리사', '제니']);
Idol blackPink2 = const Idol('블랙핑크', ['지수', '로제', '리사', '제니']);
 
print(blackPink == blackPink2); // true

1) Getter , Setter

void main() {
  Idol blackPink = Idol('블랙핑크', ['지수', '로제', '리사', '제니'],); // new 안써도 됨
  
  //get
  print(blackPink.firstMember); // 지수

  
  //set 
  blackPink.firstMember = '코드팩토리';
  print(blackPink.firstMember); // 코드팩토리
}

getter 를 함수로 구현해도 되지만,  가져오는 함수라는 약속

setter는 현대에선 거의안씀  -> final ,const 권장하는 클래스의 규칙에 위배되기때문이다.

  // getter
  String get firstMember{
    return this.members[0];
  }
  //setter 
  set firstMember(String name){
    this.members[0] = name;
  }

이름앞에 _ 를 붙히면 private다. 

클래스명 , 변수 ,함수, 생성자 모두 사용가능 

class _Idol {
	final String _name;
    void _introduce(){
    	print('저희 멤버는 ${this.members}가 있습니다.');
  	}
}

2. 상속 

부모 클래스에서 선언한 변수,함수는 자식클래스에서 쓸수있지만,

자식클래스에서 별도로 선언한 변수 함수는 부모 클래스에서 쓸수 없다.  

void main() {
  print('--------Idol--------');
  Idol apink =Idol(name:'에이핑크',membersCount: 5);
  apink.sayName();
  apink.sayMembersCount();

  print('--------BoyGroup--------');
  BoyGroup bts = BoyGroup('BTS',7);
  bts.sayName();
  bts.sayMembersCount();
  bts.sayMale();
  
  print('--------GirlGroup--------');
  GirlGroup redvelvet = GirlGroup('레드벨벳',5);
  redvelvet.sayName();
  redvelvet.sayMembersCount();
  redvelvet.sayFeMale();
  
  print('--------Type Comaparision--------');
  print(apink is Idol);//  true
  print(apink is BoyGroup);// false
  print(apink is GirlGroup);// false
  
  print('--------Type Comaparision--------');
  print(bts is Idol);//true
  print(bts is BoyGroup);//true
  print(bts is GirlGroup);//false
  
  print('--------Type Comaparision--------');
  print(redvelvet is Idol); // true
  print(redvelvet is BoyGroup); //false
  print(redvelvet is GirlGroup); //true
}


// 상속 -inheritancce


class Idol{
  //이름
  String name;
  // 숫자
  int membersCount;
  
  Idol({
    required this.name,
    required this.membersCount,
  });
  
  void sayName(){
    print('저희는 ${this.name} 입니다.');
  }
  void sayMembersCount(){
    print('${this.name}은 ${this.membersCount}명의 멤버가 있습니다.');
  }
  
}

class BoyGroup extends Idol{
  BoyGroup(
    String name,
    int membersCount,
  ): super(
    name: name,
    membersCount : membersCount,
  );
  void sayMale(){
    print('저는 남자 아이돌입니다.');
  }
  
}

class GirlGroup extends Idol{
  GirlGroup(
      String name,
      int membersCount,
  ): super(
    name: name,
    membersCount:membersCount,
  );
  
    void sayFeMale(){
    print('저는 여자 아이돌입니다.');
  }
}

 

1) Override 

void main() {
  TimesTwo  tt = TimesTwo(2);
  
  print(tt.calculate());
  
  TimesFour  tf = TimesFour(2);
  
  print(tf.calculate());
}

class TimesTwo{
  final int number;
  
  TimesTwo(this.number);
  
  int calculate(){
    return number *2;
  }
}

class TimesFour extends TimesTwo{
  TimesFour(
    int number, 
  ) :super(number);
  
  @override
  int calculate(){
    return super.number*4;
  }
  
}

아래처럼 number만 바로 써도 된다.

 @override
  int calculate(){
    return number*4;
  }

부모 메소드를 호출해서 쓸수도 있다. 

  @override
  int calculate(){
    return super.calculate()*2;
  }

 

2) static 

: static 은 instance에 귀속되지 않고 class에 귀속된다. 

 static 변수 수정시 모든 인스턴스에 적용됨.

void main() {
  Employee seulgi = Employee('슬기');
  Employee chorong = Employee('초롱');
  
  seulgi.name ='코드팩토리';
  seulgi.printNameAndBuilding();
  chorong.printNameAndBuilding();
  
  Employee.building = '오토타워';
  
  seulgi.printNameAndBuilding();
  chorong.printNameAndBuilding();
  
  Employee.printBuilding();
}

class Employee {
  // static 은 instance에 귀속되지 않고 class에 귀속된다. 
  // 알바생이 일하고 있는 건물 
  static String? building;
  // 알바생 이름 
  String name;
  
  
  Employee(this.name);
  
  void printNameAndBuilding(){
    print('제 이름은 $name 입니다. $building 건물에서 근무하고 있습니다.');
  }
  
  // 인스턴스 없이 사용가능 
  static void printBuilding(){
    print('저는 $building 건물에서 근무중입니다.');
  }
}

 

3. Interface

: 어떤 변수,함수를 써야하는지 강제할 수 있음.

void main() {
  BoyGroup bts = BoyGroup('BTS');
  
  GirlGroup ive = GirlGroup('IVE');
  
  bts.sayName();
  ive.sayName();
}

// interface
// 어떤 변수,함수를 써야하는지 강제할 수 있음.

abstract class IdolInterface {
  String name;
  
  IdolInterface(this.name);
  
  void sayName(); // 함수 바디 안써도 됨.
}

class BoyGroup implements IdolInterface{
  String name;
  
  BoyGroup(this.name);
  
  void sayName(){
    print('제 이름은 $name입니다.');
  }
}

class GirlGroup implements IdolInterface{
  String name;
  
  GirlGroup(this.name);
  
  void sayName(){
    print('제 이름은 $name입니다.');
  }
}

 

4. generic 

void main() {
  Lecture<String,String> lecture1 =Lecture('123','lecture');
  
  lecture1.printIdType();
  
  Lecture<int,String> lecture2 =Lecture(123,'lecture2');
  
  lecture2.printIdType();
}
// generic 타입을 외부에서 받을 때 사용
class Lecture<T,X>{
  final T id;
  final X name;
  
  Lecture(this.id,this.name);
  
  void printIdType(){
    print(id.runtimeType);
  }
}

5. Object

모든 클래스는 최상위 Object 클래스를 상속받는다. 

덕분에 다음 4가지 메소드를 기본으로 쓸수있다.

때문에

클래스만 선언한  Test 클래스는 사실은  

class Test{}

아래처럼 object extends Object가 생략되어있음

class Test extends Object{}

 

'프로그래밍 언어 > Flutter' 카테고리의 다른 글

Dart 4 비동기 프로그래밍  (0) 2022.10.03
Dart 3 함수형 프로그래밍  (0) 2022.10.03
Dart 언어 기본기  (0) 2022.10.02
flutter 2강  (0) 2022.10.02
flutter 설치  (0) 2022.09.27