[TIL] Dart-this and super

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

TIL

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

๐ŸŒผ this and super

  • this : this๋Š” class ๋‚ด์˜ ๋ณ€์ˆ˜์— ์ ‘๊ทผํ•  ๋•Œ ์‚ฌ์šฉํ•˜๋Š” keyword์ด๋‹ค.
  • super : ๋ถ€๋ชจ class์˜ ๋ณ€์ˆ˜๋ฅผ ์ž์‹์—๊ฒŒ ์ƒ์†ํ•˜๊ณ  ์‹ถ์„ ๋•Œ ์‚ฌ์šฉํ•˜๋Š” keyword์ด๋‹ค.
void main() {
  Engineer codeFactory = Engineer(languages: ['dart', 'java', 'javascript'], name: '์ฝ”๋“œํŒฉํ† ๋ฆฌ', building: '์—ฌ์˜๋„ ์œ„์›Œํฌ');
  
  print(codeFactory.name);  //์ฝ”๋“œํŒฉํ† ๋ฆฌ
  print(codeFactory.building); //์—ฌ์˜๋„ ์œ„์›Œํฌ
  print(codeFactory.languages); //['dart', 'java', 'javascript']
  codeFactory.sayInfo(); //์ €์˜ ์ด๋ฆ„์€ ์ฝ”๋“œํŒฉํ† ๋ฆฌ์ž…๋‹ˆ๋‹ค. ์ œ๊ฐ€ ๊ทผ๋ฌดํ•˜๋Š” ๊ฑด๋ฌผ์€ ์—ฌ์˜๋„ ์œ„์›Œํฌ์ž…๋‹ˆ๋‹ค. ์ œ๊ฐ€ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ์–ธ์–ด๋“ค์€ dart,java,javascript ์ž…๋‹ˆ๋‹ค.
  codeFactory.sayName(); //this.name์€ ์ฝ”๋“œํŒฉํ† ๋ฆฌ, super.name์€ ์ฝ”๋“œํŒฉํ† ๋ฆฌ
}

class Employee {
  final String building;
  final String name;
  Employee(this.building, this.name);
  
  void printNameAndBuilding() {
    print('์ œ ์ด๋ฆ„์€ $name์ž…๋‹ˆ๋‹ค. $building ๊ฑด๋ฌผ์—์„œ ๊ทผ๋ฌดํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค.');
  }
}

// ์‚ฌ์šฉํ•  ์ค„ ์•„๋Š” ์–ธ์–ด - ๋ฆฌ์ŠคํŠธ
class Engineer extends Employee {
  final List<String>? languages;
  Engineer({this.languages, name, building}) : super(building, name);
  
  void sayInfo() {
    print('์ €์˜ ์ด๋ฆ„์€ ${super.name}์ž…๋‹ˆ๋‹ค. ์ œ๊ฐ€ ๊ทผ๋ฌดํ•˜๋Š” ๊ฑด๋ฌผ์€ $building์ž…๋‹ˆ๋‹ค. ์ œ๊ฐ€ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ์–ธ์–ด๋“ค์€ ${languages?.join(',')} ์ž…๋‹ˆ๋‹ค.');
  }
  
  //์ƒ์†์„ ํ†ตํ•ด name, building์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๊ฒŒ๋˜๋ฏ€๋กœ ์—ฌ๊ธฐ์„œ this.name == super.name์ด ๊ฐ™์€ ๊ฐ’์„ ๊ฐ–๊ฒŒ ๋œ๋‹ค.
  //์ƒ์†๋ฐ›์€ property๋ฅผ ์ž์‹์ด ๊ทธ๋Œ€๋กœ ์‚ฌ์šฉํ•˜๋ฏ€๋กœ ๊ฐ’์ด ๋™์ผํ•˜๋‹ค๊ณ  ์ดํ•ดํ•  ์ˆ˜ ์žˆ๋‹ค.
  void sayName() {
    print('this.name์€ $name, super.name์€ ${super.name}');
  }
}

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

profile
Turtle Never stop

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