Notice
Recent Posts
Recent Comments
관리 메뉴

Developer Gonie

[2주차] 31. static멤버변수(=클래스변수) 사용시 주의할 점* 본문

K-DigitalTraining 강의/1. Java

[2주차] 31. static멤버변수(=클래스변수) 사용시 주의할 점*

이대곤 2022. 5. 23. 15:56

* statc변수의 다른 이름은 클래스 변수이다.

  객체가 생성되기 전부터 메모리에 올라가는 변수로, 같은 클래스로 객체를 여러개 생성하더라도 공유가 되어
  아래와 같은 출력결과가 나오는 것이다.

코드

class Var{
	static int a; // static 변수
	int b; // instance변수
	
	void increment() {
		int c=0; // 지역변수
		a++;
		b++;
		c++;
		System.out.println("a:"+a);
		System.out.println("b:"+b);
		System.out.println("c:"+c);
	}
}//Var

public class Ex05_07_변수 {
	public static void main(String[] args) {
		
		Var v1 = new Var();
		v1.increment();
		v1.increment();
		System.out.println();
		
		Var v2 = new Var();
		v2.increment();
		v2.increment();
		System.out.println();
		
		Var v3 = new Var();
		v3.increment();
		v3.increment();
		System.out.println();
	}
}

실행결과

a:1
b:1
c:1
a:2
b:2
c:1

a:3
b:1
c:1
a:4
b:2
c:1

a:5
b:1
c:1
a:6
b:2
c:1
Comments