본문 바로가기

Dart

[Dart] Class - 상속/Inheritance

void main() {
  House house1 = new House(4, 2);
  house1.aboutFloors();
  house1.aboutRooms();

  print('------------- APT -------------');
  Apt apt1 = new Apt(5, 3, 'Rome');
  apt1.aboutFloors();
  apt1.aboutRooms();
  apt1.aboutName();

  print('------------- Villa -------------');
  Villa villa1 = new Villa(1, 2, 'Milano');
  villa1.aboutFloors();
  villa1.aboutRooms();
  villa1.aboutName();
}

class House {
  // private variable
  int _rooms;
  int _floors;

  House(this._rooms, this._floors);

  void aboutFloors() {
    print('This house has $_floors floors.');
  }

  void aboutRooms() {
    print('This house has $_rooms rooms.');
  }
}

// extends - 상속/Inheritance

class Apt extends House {
  String _name;
  # 부모 생성자 호출 방법, 파라미터은 달라도 됨
  # 부모 생성자의 변수 타임과 동일하게 선언
  Apt(int _rooms1, int _floors1, this._name) : super(_rooms1, _floors1);

  void aboutName() {
    print('APT name is $_name.');
  }
}

class Villa extends House {
  String _name;

  Villa(int _rooms, int _floors, this._name) : super(_rooms, _floors);

  void aboutName() {
    print('Villa name is $_name.');
  }
}


--------------------------------------------[result]

This house has 2 floors.
This house has 4 rooms.
------------- APT -------------
This house has 3 floors.
This house has 5 rooms.
APT name is Rome.
------------- Villa -------------
This house has 2 floors.
This house has 1 rooms.
Villa name is Milano.

'Dart' 카테고리의 다른 글

[Dart] Class - Static  (0) 2021.05.27
[Dart] Class - Method override  (0) 2021.05.27
[Dart] Class - getter, setter  (0) 2021.05.27
[Dart] Class - 선언 및 생성자  (0) 2021.05.27
[Dart] Null Safety  (0) 2021.05.12