guricode

객체지향 프로그래밍 - static 본문

앱/Flutter&Dart

객체지향 프로그래밍 - static

agentrakugaki 2025. 7. 4. 23:44
  • static

정의 - static은 선언된 class에 종속된다.

void main() {
 
}

class Employee {
  
  static String? building;
  final String name;

  Employee(
    this.name,
  );

  void printNameAndBuilding() {
    print('My name is $name. $building is my workplace');
  }

  static void printBuilding() {
    print('im working on $building');
  }
}

//static String? building;

class Employee 안에 static으로 null이 포함될수 있는 String 값인 building를 만들었다.

여기서 static은 instance가 아닌 class에 귀속된다 무슨뜻일까?

void main() {
  **Employee seulgi = Employee('seulgi');
  Employee chocho = Employee('chocho');

  seulgi.printNameAndBuilding(); //My name is seulgi. null is my workplace
  chocho.printNameAndBuilding(); //My name is chocho. null is my workplace**
  
}

class Employee {
 
  static String? building;
  final String name;

  Employee(
    this.name,
  );

  **void printNameAndBuilding() {
    print('My name is $name. $building is my workplace');
  }**

  static void printBuilding() {
    print('im working on $building');
  }
}

// void printNameAndBuilding()

viod로 return 값을 가지지 않는 printNameAndBuilding라는 값은

seulgi.printNameAndBuilding(); 로 사용할수 있다.

여기서 seulgi. 옆에 붙은 printNameAndBuilding 은 Employee('seulgi') 의 instance로 사용된 method다.

Employee()에 'seulgi'라는 param이 들어간 메서드로 재탄생 하게 된 것이다.

즉, class Employee 안에 printNameAndBuilding()은 Instance로 사용될수 있다.

하지만 static으로 만들어진 building은 각 instance의 값이 들어가지 않고 null이 나온다.

값을 넣지 않아기 때문이다.

*그렇다면 static String? building 은 어떻게 class에 종속된다는 말일까

void main() {
  Employee seulgi = Employee('seulgi');
  Employee chocho = Employee('chocho');

  seulgi.printNameAndBuilding();//My name is seulgi. null is my workplace
  chocho.printNameAndBuilding();//My name is chocho. null is my workplace

  **Employee.building = 'OTO';

  seulgi.printNameAndBuilding();//My name is seulgi. OTO is my workplace
  chocho.printNameAndBuilding();//My name is chocho. OTO is my workplace
  
  Employee.printBuilding(); //im working on OTO**
  
}

class Employee {
 
  **static String? building;**
  final String name;

  Employee(
    this.name,
  );

  void printNameAndBuilding() {
    print('My name is $name. $building is my workplace');
  }

  **static void printBuilding() {
    print('im working on $building');
  }**
}

// Employee.building = 'OTO';

이렇게 Employee class type으로 직접 값을 넣어줘야 값이 바뀐다.

즉, static은 instance에 영향을 받지 않는다.

class를 직접 호출하여 method안에 직접 값을 넣어야한다.

그러면 class의 building이라는 값이 정해지게 되고 모든 instance의 building에 영향을 끼친다.

instance들은 class를 따온 것이기 때문이다.

static을 간단하게 배웠다.