[Java] 전역 변수(Global variable)
Java에는 C언어와 똑같은 방식으로 전역 변수를 선언할 수 있지만 사용하는 방법은 다르다. Java에서 전역 변수를 개념적으로 이해하기 위해선 Java에는 전역 변수가 없다고 생각하는 것이 편하고, 실제로 자바엔 전역 변수라는 개념이 없다는 설명을 아래와 같이 많이 찾아볼 수 있다.
- Truly global variables do not exist in Java
- Java actually doesn't have the concept of Global variable
- Global variables are not technically allowed in Java
C언어의 전역 변수는 아래와 같이 사용이 가능하다.
int global_var = 1;
int main() {
printf("%d", global_var);
return 0;
}
실행 결과:
1
반면 Java에서 전역 변수 사용은 아래와 같다.
public class Main {
public int instance_var = 1;
public static int class_var = 2;
public static void main(String[] args) {
Main m = new Main();
System.out.println(m.instance_var);
System.out.println(class_var);
}
}
실행 결과:
1
2
인스턴스 변수(instance_var)는 객체를 생성해야만 호출이 가능해, Main m = new Main();을 통해 객체를 생성한 후 m.instance_var로 사용이 가능하며, 생성자에서 사용되는 this도 같은 맥락으로 이해할 수 있다.(파이썬에선 self가 this와 비슷한 역할을 하는 것으로 생각할 수 있다.) 반면 클래스 변수(class_var)는 객체의 생성없이도 class_var만으로 바로 호출이 가능하다.
출처
Java - When a global variable is declared and initialized with a value, the what happens while object creation?
When a global variable is declared and initialized with a value, then while creating object of the class, is the global variable again gets initialized and gets a new memory? class A{ int a = 10;...
stackoverflow.com
2. https://www.geeksforgeeks.org/using-static-variables-in-java/
Using Static Variables in Java - GeeksforGeeks
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
www.geeksforgeeks.org
3. https://www.edureka.co/community/1856/how-can-we-define-global-variables-in-java
How can we define global variables in java
I want to call the variables from anywhere, for which I need to declare them as global. How to do that?
www.edureka.co