[Dart] 5. 생성자

허성재's avatar
Sep 26, 2024
[Dart] 5. 생성자
class Dog { String name; int age; String color; int thirsty; Dog(String name, int age, String color, int thirsty) : this.name = name, this.age = age, this.color = color, this.thirsty = thirsty; } class Cat { String name; int age; String color; int thirsty; Cat(this.name, this.age, this.color, this.thirsty); }
일반적인 생성자는 이렇다.
class Dog { int age; String name; // {}를 쓰면 선택해서 쓸수 있다. 선택적 매개변수 // required를 쓰면 반드시 받아야한다. // cascade .. Dog({required this.age, required this.name}); } class Cat { int? age; String? name; Cat({this.age, this.name = "토토"}); void cry() { print("야옹"); } } void main() { Dog d = Dog(name: "토토", age: 10); Cat c = Cat(age: 15)..cry(); print("개는 : ${d}"); print("고양이는 : ${c}"); }
{}를 쓰면 빌더 패턴처럼 사용이 가능하다. 필요한것만 넣어서 쓸수 있다.
생성과 동시에 init 메서드를 실행 시키고 싶은 경우 .. 을 붙혀 메소드를 적는다.
class User { int id; String username; String password; User(this.id, this.username, this.password); User.hello( {required this.id, required this.username, required this.password}); User.fromJson(Map<String, dynamic> json) : this.id = json["id"], this.username = json["username"], this.password = json["password"]; } void main() { User u1 = User(1, "ssar", "1234"); User u2 = User.hello(id: 1, username: "ssar", password: "1234"); User u3 = User.fromJson({"id": 1, "username": "ssar", "password": "1234"}); print(u1.username); print(u2.username); print(u3.username); }
Share article

heo-gom