
- 여러 개의 객체가 하나의 변수를 공유할 때 static을 붙이는데 이를 정적 멤버라고 한다.
- 정적 변수와 정적 메소드가 있음
정적 변수
- jvm에 적재 되는 순간 생성 되며 객체가 사라져도 정적 변수는 존재하고 프로그램이 종료되어야 비로소 사라진다.
- 정적 멤버중 하나의 유형으로 클레스당 하나만 생성가능하며 타입 앞에 static을 붙인다. 사용 방법은 클레스 명 뒤에 .을 붙이면 된다.
정적 메소드
- static을 메소드 앞에 붙여서 만들면 되며 호출 방법은 클레스 명. 정적 메소드 명 이다.
package ex05;
public class MyMathTest {
public static void main(String[] args) {
System.out.println("10의 3승은 "+MyMath.power(10,3) );
}
}
math 클레스 생성
package ex05;
public class MyMath {
public static int abs(int x) {
return x > 0 ? x : -x;
}
public static int power(int base, int exponent) {
int result = 1;
for (int i = 1; i <= exponent; i++) {
result = result * base;
}
return result;
}
}
정적 블록
- 클레스가 메모리에 로드 될 때 한번만 실행되는 문장들의 집합
- 정적 초기화 블록이라고도 한다.
- 정적 변수들을 초기화 하는 용도로 사용
public class Test{
static int number;
static String s;
static {
number = 23:
s = "Hello World!";
}
public static void main(String args[]) {
System.out.println("number:" + number);
System.out.println("s:" + s);
Share article