ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [개발일지] Dart 입문 2: Object Oriented Programming
    Study/Development 2022. 8. 18. 01:05

     

    <인프런 코드팩토리 강의 수강일지>

     

    1. class 선언

    void main() {
      Idol blackPink = Idol('블랙핑크', ['지수', '제니', '리사', '로제']);
      Idol bts = Idol.fromList([
        ['RM', '진', '슈가', '제이홉', '지민', '뷔', '정국'],
        'BTS',
      ]); // 리스트로 값을 줄 수 있다.
    
      print(blackPink.name); // 블랙핑크
      print(blackPink.members); // [지수, 제니, 리사, 로제]
      blackPink.sayHello(); // 안녕하세요 블랙핑크입니다.
      blackPink.introduce(); // 저희 멤버는 [지수, 제니, 리사, 로제]가 있습니다.
    
      print(bts.name); // BTS
      print(bts.members); // [RM, 진, 슈가, 제이홉, 지민, 뷔, 정국]
      bts.sayHello(); // 안녕하세요 BTS입니다.
      bts.introduce(); // 저희 멤버는 [RM, 진, 슈가, 제이홉, 지민, 뷔, 정국]가 있습니다.
    }
    
    // Idol class
    
    class Idol {
      String name;
      List<String> members;
    
      Idol(this.name, this.members);
    
      Idol.fromList(List values)
          : this.members = values[0],
            this.name = values[1];
    
      void sayHello() {
        print('안녕하세요 ${this.name}입니다.');
      }
    
      void introduce() {
        print('저희 멤버는 ${this.members}가 있습니다.');
      }
    }

     

    2. getter / setter

    void main() {
      Idol blackPink = Idol('블랙핑크', ['지수', '제니', '리사', '로제']);
      Idol bts = Idol.fromList([
        ['RM', '진', '슈가', '제이홉', '지민', '뷔', '정국'],
        'BTS',
      ]);
    
      print(blackPink.firstMember); // 지수
      print(bts.firstMember); // RM
    
      blackPink.firstMember = '최불암';
      bts.firstMember = '윤여정';
    
      print(blackPink.firstMember); // 최불암
      print(bts.firstMember); // 윤여정
    }
    
    // getter / setter
    // 값을 가져오고 변경할 때
    
    class Idol {
      String name;
      List<String> members;
    
      Idol(this.name, this.members);
    
      Idol.fromList(List values)
          : this.members = values[0],
            this.name = values[1];
    
      void sayHello() {
        print('안녕하세요 ${this.name}입니다.');
      }
    
      void introduce() {
        print('저희 멤버는 ${this.members}가 있습니다.');
      }
    
      // getter
      String get firstMember {
        return this.members[0];
      }
    
      // setter
      set firstMember(String name) {
        this.members[0] = name;
      }
    }

    3. Private 속성

    // _ 언더바를 붙이면, 한 파일 내에서만 사용할 수 있다.
    class _Idol {...}; // 클래스
    this._members = values[0]; // 변수
    _sayhello(){...} // 함수

     

    4. 상속: 자식 / 부모 Class

    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('Red Velvet', 5);
    
      redVelvet.sayName();
      redVelvet.sayMembersCount();
      redVelvet.sayFemale(); // 부모클래스에서는 사용 불가
    
      print('----- Type Comparison -----');
      print(apink is Idol);
      print(apink is BoyGroup);
      print(apink is GirlGroup);
    
      print('----- Type Comparison2 -----');
      print(bts is Idol);
      print(bts is BoyGroup);
      print(bts is GirlGroup);
      
      print('----- Type Comparison3 -----');
      print(redVelvet is Idol);
      print(redVelvet is BoyGroup);
      print(redVelvet is GirlGroup);
    }
    
    // 상속 - inheritance
    //
    // 상속을 받으면 부모 클래스의 모든 속성을
    // 자식 클래스가 부여받는다.
    
    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('저는 여자 아이돌입니다.');
      } // 자식 클래스에서 선언한 값은 부모 클래스에서 사용 불가하다.
    }

     

    5. override: 덮어쓰기

     - 부모로부터 상속받은 값, 함수를 덮어쓸 수 있다.

    void main() {
      TimesTwo tt = TimesTwo(2);
    
      print(tt.calculate());
    
      TimesFour tf = TimesFour(2);
    
      print(tf.calculate());
    }
    
    // method - function (class 내부에 있는 함수)
    // override - 덮어쓰다 (우선시하다)
    
    class TimesTwo {
      final int number;
    
      TimesTwo(this.number);
    
      // method
      int calculate() {
        return number * 2;
      }
    }
    
    class TimesFour extends TimesTwo {
      TimesFour(
        int number,
      ) : super(number);
    
      @override
      int calculate() {
    //     return super.number * 4;
        return super.calculate() * 2; // super 키워드 사용하여 변수나 함수 가져올 수 있다.
      }
    }

     

    6. static

     - static은 instance에 귀속되지 않고 class에 귀속된다. (전체에 해당)

    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; // class 전체에 귀속
      //알바생 이름
      String name; // 각 instance 값
    
      Employee(
        this.name,
      );
    
      void printNameAndBuilding() {
        print('제 이름은 $name입니다. $building 건물에서 근무하고 있습니다.');
      }
    
      static void printBuilding() {
        print('저는 $building 건물에서 근무중입니다.');
      }
    }

     

    7. Interface

     - 기본적인 포맷을 제시

    void main() {
    BoyGroup bts = BoyGroup('BTS');
      GirlGroup redVelvet = GirlGroup('레드벨벳');
    
      
      bts.sayName(); // 제 이름은 BTS입니다.
      redVelvet.sayName(); // 제 이름은 레드벨벳입니다.
      
      print(bts is IdolInterface); // true
      print(bts is BoyGroup); // true
      print(bts is GirlGroup); // false
      
      print(redVelvet is IdolInterface); // true
      print(redVelvet is BoyGroup); // false
      print(redVelvet is GirlGroup); // true
    }
    
    
    // interface
    // abstract 키워드 사용하여
    // instance로 사용 불가하도록 할 수 있다.
    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입니다.');
      }
      
    }

     

    8. generic

     - 타입을 외부에서 받을 때 사용

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

     

    10. OOP

     - 객체 지향 프로그래밍

    void main() {
    Test test = Test();
      
      // 모든 클래스는 Object라는 클래스를 상속받기 때문에
      // 아래 4개 값을 기본으로 가진다
      test.hashCode;
      test.runtimeType;
      test.toString();
      test.noSuchMethod(); 
    }
    
    // OOP: Object Oriented Programming
    // 객체 지향 프로그래밍
    
    class Test{}

     

    반응형

    댓글

© 2023. titann all rights reserved