Dart class(2)

IngCoding·2023년 6월 6일
1
// 1. Cascade Notation 

class Player {
  String name;
  int xp;
  String team;
  
  Player({required this.name, required this.xp, required this.team});

  void sayHello() {
    print("Hi my name is $name"); 
  }
}
// Cascade notation 적용
vodi main() {
    var nico = Player(name: 'nico', xp: 1200, team: 'red')
    ..name = 'las'
    ..xp = 12000
    ..team = 'blue';

    // 위 코드는 아래와 같음 
    // var nico = Player(name: 'nico', xp: 1200, team: 'red');
    // nico.name = 'las';
    // nico.xp = 120000;
    // nico.team = 'blue';

}

// 2. Enum 
// 우리가 실수하지 않도록 도와주는 클래스 

enum Team { red, blue }

enum XPLevel { beginner, medium, pro }

void main() {
  var nico = Player(name: 'nico', XPLevel.medium, Team.red)
    ..name = 'las'
    ..xp = XPLevel.pro // enum 안에 설정된 요소만 사용할 수 있다 
    ..team = Team.blue;
}



// 3. Abstract Classes
다른 클래스들이 직접 구현 해야하는 메소드들을 모아놓은 일종의 청사진으로,
객체를 생성할 수 없는 클래스 ;.

abstract class Human { // 추상화 클래스는 특정 메소드를 구현하도록 강제
  void walk();
}

enum Team { red, blue }

enum XPLevel { beginner, medium, pro }

// Playser 클래스에 추상화클래스 Human을 가져와서 walk 메소드를 쓸 수 있게 해준다
class Player extends Human {
  String name;
  XPLevel xp;
  Team team;

  Player({required this.name, required this.xp, required this.team});


  void walk {
    print('im walk');
  }
  void sayHello() {
    print("Hi my name is $name, XP is $xp, Team is $team");
  }
}

  // Coach 클래스가 Human 추상화 클래스를 받아서 walk 메소드의 방식 변경
  class Coach extends Human {
    void walk() {
      print('the coach is walking');
    }
  }

void main() {
  var nico = Player(name: 'nico', XPLevel.medium, Team.red)
    ..name = 'las'
    ..xp = XPLevel.pro
    ..team = Team.blue;
}


// 4. Inheritance

class Human {
  final String name; 
  Human({required this.name}); // 확장한 부모클래스가 확장자 포함 , 생성자
  void sayHello() {
    print("Hi my name is $name");
  }
}

enum Team { blue, red };

class Player extends Human { // extends로 확장
  final Team team;  

  Player({
    required this.team,
    required String name,
  }) : super(name: name);   // super는 상속한 부모 클래스의 프로퍼티에 접근하거나 메소드를 호출할 수 있게 해줌

   // 대체
  void sayHello() {
    super.sayHello();
    print('and I play for ${team}');
  }
}

void main() {
  var player = Player(
    team: Team.red,     
    );  
}

// 5. Mixins : 생성자가 없는 클래스
// 다른 클래스의 부모 클래스가 되지 않으면서 다른 클래스에서 사용 가능한 메서드를 포함하는 클래스

class Strong {
  final double strengthLvel = 1500.99;
}
class QuickRunner {
  void runQuick() {
    print('runnnnnnnnnnnnn!');
  }
}

class Tall {
  final double height = 1.99;
}


class Player with Strong, QuickRunner, Tall { // with를 통해 Quick, Strong 클래스에 있는 프로퍼티와 메소드를 Player에 담음
  final Team team; // super 가 없이도 접근 가능 
}

// Mixins의 핵심은 with 키워드를 통해 클래스를 여러번 활용 
class Horse with Strong, QuickRunner {
}

class Kid with QuickRunner {
}

void main() {
  var player = Player(
    team: Team.red,     
    );  
    player.runQuick
profile
Data & PM

0개의 댓글