-
[dart] dart 언어 기본 간단 정리1(class, getter setter, static)Dart 2023. 1. 7. 17:24
dart 의 실행은 main() 메소드가 있는곳에서 실행 해야함
class 생성 및 사용
(public member 변수)
class User { // public 으로 사용 String name; int age; // {} 를 사용해서 옵션으로 지정 가능. 호출하는 곳에서 parameter 값을 직접 명시해서 사용 User({this.name = "cis"}); // 생성자에 name 의 기본값 지정. }
<User class>
void main(){ User user = User(); // user instance 생성. 빈 값으로 넣거나 옵션으로 지정한 parameter 명시해줌 User user1 = User(name: "newCis"); user1.name = "ccc"; // 이렇게 직접 접근해서 사용하지 말고 getter setter 를 사용하는게 좋음. }
<main 메소드 실행하는 곳>
(private member 변수)
dart 에서는 private 지정을 변수명 앞에 _(언더바) 를 붙여서 지정함
class User { // private 으로 지정해서 사용 String _name; int _age; User({this.name = "cis"}) : _name = name; }
<User class>
getter setter 지정
class Car { int _wheels = 4; // 다른 클래스에서 접근하지 못하도록 private 으로 지정하면 getter setter 를 지정해서 읽고 쓸 수 있도록 해줘야함 int get wheels{ return _wheels; } setter 지정은 둘 중 원하는 형태로 만들면 됨 set wheels(int wheel){ _wheels = wheel; } void setWheels(int wheel) { _wheels = wheel; } }
<Car class>
main() { Car car = Car(); int wheel = car.wheels; print("car wheels : $wheel"); // car wheels : 4 가 출력됨 car.wheels = 10; int newWheels = car.wheels; print("car wheels : $newWheels"); // car wheels : 10 이 출력됨 car.setWheels(20); int newWheels2 = car.wheels; print("car wheels : $newWheels2"); // car wheels : 20 이 출력됨 }
<main 메소드 실행하는 곳>
static
class 안에 static 을 사용하면 class 안에는 존재하지만 instance 안에는 존재하지 않는다.
class명.static 변수명으로 호출해서 사용할 수 있다.
class Car { static int temperature = 20; static const String logo = "kia"; }
void main() { print(Car.temperature); // 20 출력됨 print(Car.logo); // kia 출력됨 }
'Dart' 카테고리의 다른 글
[dart] dart 문법 간단 정리 2 (0) 2023.02.17 [dart] dart 문법 간단 정리 1 (0) 2023.02.17 [dart] dynamic 과 object 의 차이점 (0) 2023.01.06