기본적으로 class property 변경하려면 아래와 같이 작성해야한다.
class Player {
String name; // 'final'을 제거
int age;
String country;
Player({
required this.name,
required this.age,
required this.country,
});
}
void main() {
var player1 = Player(name: 'jinjin', age: 25, country: 'seoul')
player.name = 'geegee';
player.age = 12;
}
하지만 dart의 cascade notation을 사용하면 간단하게 접근하여 변경할 수 있다.
class Player {
String name; // 'final'을 제거
int age;
String country;
Player({
required this.name,
required this.age,
required this.country,
});
}
void main() {
var player1 = Player(name: 'jinjin', age: 25, country: 'seoul')
..name = "jin" // 이제 'name'을 변경 가능
..age = 12
..country = "jui";
print(player1.name); // 출력: jin
player1
..name = "123";
}
enum은 개발자가 코드를 실수하지 않도록 규정해주는 역할을 한다.
enum Country { seoul, daegu } // 따옴표는 사용하지 않음
class Player {
String name; // 'final'을 제거
int age;
Country country; // 타입은 String이 아닌 enum으로
Player({
required this.name,
required this.age,
required this.country,
});
}
void main() {
var player1 = Player(name: 'jinjin', age: 25, country: Country.daegu) // enum의 속성으로 설정
..name = "jin" // 이제 'name'을 변경 가능
..age = 12
..country = "jui";
print(player1.name); // 출력: jin
player1
..name = "123";
}
추상화 클래스는 직접 사용할 수 없고 내용이 없는 매서드를 구현하여 하위 클래스들이 해당 매서드를 반드시 구현하도록 강요한다.
abstract class Animal {
void makeSound(); // 추상 메서드: 소리를 내는 방법은 정해지지 않았음
}
class Dog extends Animal {
void makeSound() {
print('Bark'); // Dog 클래스에서 소리를 내는 방법을 정의함
}
}
class Cat extends Animal {
void makeSound() {
print('meow'); // Cat의 소리
}
}
void main() {
var dog = Dog();
dog.makeSound(); // 출력: Bark
var cat = Cat();
cat.makeSound(); // 출력: Meow
}
상속의 클래스에서 가장 중요한 개념으로 상속 받은 자식 클래스는 부모 클래스에 접근할 수 있게 된다.
// 부모 클래스 정의
class Animal {
String name;
// 부모 클래스 생성자
Animal(this.name) {
print('Animal created: $name');
}
void makeSound() {
print('$name makes a generic animal sound');
}
}
// 자식 클래스 정의, Animal 클래스를 상속받음
class Dog extends Animal {
int age;
// 자식 클래스 생성자
Dog(String name, this.age) : super(name) {
print('Dog created: $name, Age: $age');
}
void makeSound() {
super.makeSound();
print('$name barks');
}
}
void main() {
var dog = Dog('Buddy', 3);
dog.makeSound(); // 출력: Buddy barks
}
이렇게 상속을 받아 같은 코드를 줄일수도, 부모 클래스의 기능을 확장하거나 변경할 수도 있다.
mixin은 dart의 기능 중 하나로, 다른 여러 클래스를 참조 할 수 있다.
mixin은 상속과 다른 개념으로 부모와 자식의 참조 관계가 아닌 단순히 mixin의 매서드를 가져온다는 개념으로 생각해야한다.
// Mixin으로 사용할 클래스 정의
class CanFly {
void fly() {
print("I can fly!");
}
}
// 다른 클래스에서 mixin 사용
class Bird with CanFly {
void chirp() {
print("Chirp chirp!");
}
}
class Plane with CanFly {
void engineSound() {
print("Vroom vroom!");
}
}
void main() {
var bird = Bird();
bird.chirp(); // 출력: Chirp chirp!
bird.fly(); // 출력: I can fly!
var plane = Plane();
plane.engineSound(); // 출력: Vroom vroom!
plane.fly(); // 출력: I can fly!
}