기술(Tech, IT)/자바(Java)

[Java] 전역 변수(Global variable)

Daniel803 2022. 9. 18. 14:09

 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만으로 바로 호출이 가능하다.

 

출처

1. https://stackoverflow.com/questions/58345111/java-when-a-global-variable-is-declared-and-initialized-with-a-value-the-what

 

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

4. https://shm-m.github.io/blog/global_variable

'기술(Tech, IT) > 자바(Java)' 카테고리의 다른 글

[Java] 'Parent' is abstract; cannot be instantiated  (0) 2022.09.29
[Java] Queue(큐) 선언 및 사용  (0) 2022.09.27
[Java] 생성자(Constructor)  (0) 2022.09.14
[Java] JAR(Java Archive)  (0) 2021.09.18
[Java] instanceof  (0) 2021.08.23