java/basic 문법
scope, static
일상코더
2022. 9. 27. 20:18
변수가 선언된 블럭이 그 변수의 사용범위이다.
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);
}
public static void main(String[] args) {
System.out.println(globalScope); //오류 // 인스턴스화 해서 사용하거나 static 이용
System.out.println(localScope); //오류
System.out.println(value); //오류
}
}
static
- 같은 클래스 내에 있음에도 해당 변수들을 사용할 수 없다.
- main 메소드는 static 이라는 키워드로 메소드가 정의되어 있다. 이런 메서드를 static 한 메소드 라고 한다.
- static한 필드(필드 앞에 static 키워드를 붙힘)나, static한 메소드(항상 사용하는 main method)는 Class가 인스턴스화 되지 않아도 사용할 수 있다.
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);
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 하게 선언된 변수는 값을 저장할 수 있는 공간이 하나만 생성된다.
// 그러므로 인스턴스가 여러개 생성되도 static한 변수는 하나다.
}
}
- golbalScope같은 변수(필드)는 인스턴스가 생성될때 생성되기때문에 인스턴스 변수라고 한다.
- staticVal같은 static한 필드를 클래스 변수라고 한다.
- 클래스 변수는 레퍼런스.변수명 하고 사용하기 보다는 클래스명.변수명 으로 사용하는것이 더 바람직하다고 하다.
- ex) VariableScopeExam.staticVal