JAVA
스태틱(STATIC)
🤖 Play with Android 🤖
2021. 7. 5. 13:10
728x90
static 변수와 메소드는 클래스에서 생성된 모든 인스턴스가 공유하는 자원이다
그리고 인스턴스를 만들지 않고도 클래스에서 직접 호출할 수 있다.
아래 지문을 보면서 살펴보자
우선 알아둬야할 베이스는 변수가 선언된 블럭이 그 변수의 사용범위라는 것이다.
public class ValableScopeExam{
int globalScope = 10; //클래스의 속성으로 선언된 변수
public void scopeTest(int value){
int localScope = 10; //메소드 안에서 선언된 변수
System.out.println(globalScope);
System.out.println(localScpe);
System.out.println(value);
}
}
- 클래스의 속성으로 선언된 변수 globalScope 의 사용 범위는 클래스 전체 이다.
- 매개변수로 선언된 int value 는 블럭 바깥에 존재하기는 하지만, 메소드 선언부에 존재하므로 사용범위는 해당 메서드 블럭내이다.
- 메소드 블럭내에서 선언된 localScope 변수의 사용범위는 메소드 블럭내이다.
이것을 메인메소드에서 사용해보자
public class VariableScopeExam {
int globalScope = 10;
public void scopeTest(int value){
int localScope = 20;
System.out.println(globalScope);
System.out.println(localScope);
System.out.println(value);
}
public static void main(String[] args) {
System.out.println(globalScope); //오류
System.out.println(localScope); //오류
System.out.println(value); //오류
}
}
위의 코드를 보면 같은 VariableScopeExam 이라는 클라스 안에 있는데도 globalScope 변수를 사용 할 수 없다.
이유는 main은 static한 메소드이기 때문이다. static한 메소드에서는 static 하지 않은 필드를 사용 할 수 없다.
public class VariableScopeExam {
int globalScope = 10;
static int staticVal = 7;
public void scopeTest(int value){
int localScope = 20;
}
public static void main(String[] args) {
System.out.println(staticVal); //사용가능
}
}
- main 메소드는 static 이라는 키워드로 메소드가 정의되어 있다. 이런 메서드를 static 한 메소드 라고 한다.
- static한 필드(필드 앞에 static 키워드를 붙힘)나, static한 메소드는 Class가 인스턴스화 되지 않아도 사용할 수 있다.
static의 또다른 특성은 static한 변수는 공유된다는 것이다.
- static하게 선언된 변수는 값을 저장할 수 있는 공간이 하나만 생성된다. 그러므로, 인스턴스가 여러개 생성되도 static한 변수는 하나다.
ValableScopeExam v1 = new ValableScopeExam();
ValableScopeExam v2 = new ValableScopeExam();
v1.golbalScope = 20;
v2.golbalScope = 30;
System.out.println(v1.golbalScope); //20 이 출력된다.
System.out.println(v2.golbalScope); //30이 출력된다.
v1.staticVal = 10;
v2.staticVal = 20;
System.out.println(v1.statVal); //20 이 출력된다.
System.out.println(v2.statVal); //20 이 출력된다.(static한 변수는 하나이기 때문)