* 하기 내용은 프로그래머스 자바 입문 강의 및 소스코드 + 구글링 + 제 개인적 견해로 작성된 내용입니다.
2. 변수의 scope와 static
1) 변수의 사용범위 = 변수가 선언 된 블럭
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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);
}
}
Colored by Color Scripter
|
- 프로그램상에서 사용되는 변수들은 사용 가능한 범위를 가진다. (=변수의 scope)
- 클래스 속성으로 선언된 변수 globalScope의 사용범위: 클래스 전체
- 매개변수로 선언 된 변수 int value의 사용범위: 메소드 블럭 內
- 메소드 블럭내에서 선언 된 localScope의 사용범위: 메소드 블럭 內
2) main메소드에서 사용하기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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); //오류
}
}
Colored by Color Scripter
|
- 같은 클래스 안에 있지만, globalScope 변수를 사용 할 수 없다.
- main은 static한 메소드이다. static한 메서드에서는 static 하지 않은 필드를 사용 할 수 없다.
3) static
1
2
3
4
5
6
7
8
9
10
11
12
13
|
public class VariableScopeExam {
int globalScope = 10;
static int staticVal = 7;
public void scopeTest(int value){
int localScope = 20;
System.out.println(staticVal); //사용가능
}
public static void main(String[] args) {
System.out.println(staticVal); //사용가능
}
}
Colored by Color Scripter
|
- 같은 클래스 내에 있음에도 해당 변수들을 사용 할 수 없다
- main메소드는 static이라는 키워드로 메소드가 정의되어 있다. 이런 메소드를 static한 메소드라고 한다.
- 모든 class는 인스턴스화 하지 않으면, 사용 할 수 없다.
- 그러나 static한 필드나, static한 메소드는 class가 인스턴스화 되지 않아도 사용할 수 있다.
- 객체를 생성하지 않아도 사용 할 수 있다 = new키워드로 선언해주지 않아도 사용 할 수 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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한 변수는 하나다.
- 클래스 변수는 '레퍼런스.변수명' 으로 사용하기보다, '클래스명.변수명'으로 사용하는 것이 더 바람직하다.
- v1.staticVal → VariableScopeExam.staticVal
- globalScope같은 변수(필드)는 인스턴스가 생성될 때 생성되기 때문에, 인스턴스 변수라고한다.
- staticVal 같은 static한 필드를 클래스 변수라고한다.
* static에 대한 좀 더 상세한 내용
위키독스
온라인 책을 제작 공유하는 플랫폼 서비스
wikidocs.net
'개발 이야기 > CC-Java' 카테고리의 다른 글
[1주차] 자동차 경주 게임 - Step3. 피드백(4)_추상화 (0) | 2019.07.03 |
---|---|
[1주차] 자동차 경주 게임 - Step3. 피드백(3)_Interface (0) | 2019.07.02 |
[1주차] 자동차 경주 게임 - Step3. 피드백(1)_객체 선언 (0) | 2019.06.30 |
[1주차] 자동차 경주게임 - step3 피드백 (0) | 2019.06.30 |
[1주차] 자동차 경주 게임 - Step2. 피드백(1) (0) | 2019.06.19 |