Language/Java
[Java] static
p8labs
2021. 8. 23. 17:54
728x90
반응형
static
- static에 대해서 알아봅니다.
- static은 보통 변수나 메소드 앞에 static 키워드를 붙여서 사용한다.
- 클래스 멤버라고 한다.
static 변수
- 변수에 static 키워드를 붙이면 메모리 할당을 한번만 하게된다.
- 공유변수로 사용할때 쓰게 된다.
static 변수 구현
- static 변수를 사용하면 초기화는 한번만 된다.
- 메모리에 한번만 올라가고 공유자원으로 사용할 수 있다.
public class Counter {
static int count = 0;
Counter() {
this.count++;
System.out.println(this.count);
}
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
}
}
결과
1
2
static method
- 스태틱 메소드라고 한다.
- 클래스가 로드될때 이미 메모리에 static 메소드가 올라가게 된다.
- 그렇기 때문에 스태틱 메소드는 인스턴스를 생성하지 않고 바로 쓸수 있는 메소드이다.
static method 구현
- Counter.getCount() 로 생성자 없이 바로 호출을 하였다.
- 참고로 static 메소드 안에는 static 메소드 변수만 사용할 수 있다.
public class Counter {
static int count = 0;
Counter() {
this.count++;
}
public static int getCount() {
return count;
}
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
System.out.println(Counter.getCount());
}
}
07-3 정적 변수와 메소드 (static)
이번에는 static에 대해서 알아보자. static은
wikidocs.net
728x90
반응형