Notice
Recent Posts
Recent Comments
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

충분히 쌓여가는

6.9 인스턴스 멤버 - 정적 멤버 본문

이것이 자바다/06 클래스

6.9 인스턴스 멤버 - 정적 멤버

빌드이너프 2024. 4. 1. 22:01

자바는 클래스 로더를 이용해서 클래스를 메소드 영역에 저장하고 사용한다

정적static 멤버란 메소드 영역의 클래스에 고정적으로 위치하는 멤버

따라서 정적 멤버는 객체를 생성할 필요 없이 클래스를 통해 바로 사용 가능하다

 

정적 멤버 선언

static 키워드를 추가

public class 클래스 {
  //정적 필드 선언
  static 타입 필드 = 초기값;
  
  //정적 메소드
  static 리턴타입 메소드(매개변수, ...) {...}
}
public class Calculator {
  String color;
  static double pi = 3.14159;
}
public class Calculator {
  String color;
  static int plus(int x, int y) {return x + y;}
  static int minus(int x, int y) {return x - y;}
}

 

 

정적 멤버 사용

클래스가 메모리로 로딩되면 정적 멤버를 바로 사용할 수 있는데

클래스 이름과 함께 도트(.) 연산자로 접근하면 된다

public class Calculator {
  static double pi = 3.14159;
  static int plus(int x, int y) { ... }
  static int minus(int x, int y) { ... }
}
double result1 = 10 * 10 * Calculator.pi;
int result2 = Calculator.plus(10, 5);
int result3 = Calculator.minus(10, 5);

 

정적 필드와 정적 메소드는 객체 참조 변수로도 접근 가능하다

하지만 정적 요소는 클래스 이름으로 접근하는 것이 정석이다

Calculator myCalcu = new Calculator();
double result1 = 10 * 10 * myCalcu.pi;
int result2 = myCalcu.plus(10, 5);
int result3 = myCalcu.minus(10, 5);