[TIL] Dart-Inheritance and Override

link717ยท2021๋…„ 7์›” 19์ผ
0

TIL

๋ชฉ๋ก ๋ณด๊ธฐ
43/53
post-thumbnail

๐ŸŒผ Inheritance

  • class์— extends๋ผ๋Š” keyword๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋ถ€๋ชจ class๋ฅผ ์ƒ์†๋ฐ›์„ ์ˆ˜ ์žˆ๋‹ค.

    . ์ž์‹์€ ๋ถ€๋ชจ์˜ ๋ชจ๋“  ํ•จ์ˆ˜ ๋ฐ ๋ณ€์ˆ˜๋ฅผ ์ƒ์†๋ฐ›์ง€๋งŒ ๋ถ€๋ชจ๋Š” ์ž์‹์˜ ์–ด๋– ํ•œ ๊ฒƒ๋„ ์ƒ์†๋ฐ›์ง€ ์•Š๋Š”๋‹ค.
    . ์ž์‹์€ 2๊ฐœ์˜ ์ด์ƒ์˜ ๋ถ€๋ชจ class๋ฅผ ๊ฐ€์งˆ ์ˆ˜ ์—†๋‹ค.

void main() {
  //Inheritance
  Idol seulgi = Idol(name: '์Šฌ๊ธฐ', group: '๋ ˆ๋“œ๋ฒจ๋ฒณ');
  seulgi.sayName();
  seulgi.sayGroup();
  
  //๋ถ€๋ชจ์˜ ๊ฒƒ์„ ๋ชจ๋‘ ์ƒ์† ๋ฐ›์•„์„œ ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.
  BoyGroup rm = BoyGroup('rm', 'bts');
  rm.sayName();
  rm.sayGroup();
  

  rm.sayMale();
  
  GirlGroup chorong = GirlGroup('์ดˆ๋กฑ', '์—์ดํ•‘ํฌ');
  chorong.sayFemale();
}

class Idol {
  final String? name;
  final String? group;
  //this๋Š” ํ˜„์žฌ class๋ฅผ ์˜๋ฏธํ•œ๋‹ค.
  Idol({this.name, this.group});
  
  void sayName() {
    print('์ œ ์ด๋ฆ„์€ $name์ž…๋‹ˆ๋‹ค.');
  }
  
  void sayGroup() {
    print('์ €๋Š” $group ์†Œ์†์ž…๋‹ˆ๋‹ค.');
  }
}


class BoyGroup extends Idol {
  //super๋Š” ๋ถ€๋ชจ class๋ฅผ ์˜๋ฏธํ•œ๋‹ค.
  //๋ถ€๋ชจ ํ‚ค์›Œ๋“œ์˜ ๋ฌด์–ธ๊ฐ€๋ฅผ ์“ฐ๊ณ  ์‹ถ์„ ๊ฒฝ์šฐ์— super๋ผ๋Š” keyword๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.
  BoyGroup(String name, String group) : super(name: name, group: group);
  
  void sayMale() {
    print('์ €๋Š” ๋‚จ์ž ์•„์ด๋Œ์ž…๋‹ˆ๋‹ค.');
  }
}

class GirlGroup extends Idol {
  GirlGroup(String name, String group) : super(name: name, group: group);
  
  void sayFemale() {
    print('์ €๋Š” ์—ฌ์ž ์•„์ด๋Œ์ž…๋‹ˆ๋‹ค.');
  }
}

๐ŸŒผ Override

  • ๋ถ€๋ชจ๋ฅผ ์ƒ์†๋ฐ›์€ child class์—์„œ ๋ถ€๋ชจ์˜ method(class ์•ˆ์˜ ํ•จ์ˆ˜๋ฅผ ๋ถ€๋ฅผ ๋•Œ ์“ด๋‹ค.)๋ฅผ ๋ฎ์–ด์“ฐ๊ธฐ ํ•  ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค.
  • @(decorator)์™€ ํ•จ๊ป˜ override๋ผ๋Š” keyword๋ฅผ ์„ ์–ธํ•˜์—ฌ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.
void main() {
  //Method Overriding

  Parent parent = Parent(3);
  Child child = Child(3);
  Child child2 = Child(3);
  
  print(parent.calculate());   // 3 * 3 = 9
  print(child.calculate());    // 3 + 3 = 6
  print(child2.calculate2());  // (3 * 3) + (3 * 3) = 18
}

class Parent {
  final int number;
  Parent(this.number);
  
  //Method๋ผ๊ณ  ๋ถ€๋ฅธ๋‹ค.
  int calculate() {
    return number * number;
  }
}

class Child extends Parent {
  Child(int number): super(number);
  
  //@ : decorator
  @override
  int calculate() {
    return number + number;
  }
  
  int calculate2() {
    int result = super.calculate();
    
    return result + result;
  }
}

์ถœ์ฒ˜:YOUTUBE-์ฝ”๋“œํŒฉํ† ๋ฆฌ

profile
Turtle Never stop

0๊ฐœ์˜ ๋Œ“๊ธ€