본문 바로가기

자바

11. static

static은 같은 클래스에서 나온 객체가 static이 붙은 키워드를 공유하는 문법이다. static 키워드를 붙은 요소는 객체마다 따로따로 생기지 않는다. static이 선언되지 않은 외부에서 static 키워드가 붙은 요소를 접근 시 객체를 생성하지 않고 클래스명을 이용하여 접근한다. 

 

staic의 장점은 객체생성과 상관없이 클래스에 존재하기 때문에 힙 영역에 메모리를 사용하지 않아서 메모리 효율성이 좋다는 것이다. 

 

static의 단점은 가비지 콜렉터로 삭제되지 않기 때문에 프로그램이 오랜시간 지속되면 메모리 관리가 되지 않는다는 점이다.

 

static이 사용되는 대표적인 예는 상수를 지정할 때 사용하거나 프로젝트에서 팀원끼리 약속에 의해 정해진 변수 지정시에 사용한다.. (ex. 3.141592...)

 

package com.Static;

public class MyStatic {
	public static int num1 = 0; //static 변수, 클래스 변수, MyStatic을 통해 나온 객체들은 num1을 공유, 객체가 생성되기 전에 메모리에 올라간다
	public int num2; //일반변수, 각각의 객체에 따로 생성
	
	public MyStatic(){num2 = 0;} //기본 생성자
	
	public void plusnum1() {
		num1++;
	}
	
	public void plusnum2() {
		num2++;
	}
	
	//static함수는 static변수만 접근 가능
	public static void static_plusnum1() {
		num1 = num1 + 2;
	}
	
	//일반 함수는 static변수도 접근이 가능
	public void another_static_plusnum1() {
		num1 = num1 + 3;
	}
}

 

package com.Static;

import com.Static.MyStatic.*;

public class Main {
	public static void main(String[] args) {
		MyStatic MS1 = new MyStatic();
		MyStatic MS2 = new MyStatic();
		
		MS1.plusnum1();
		System.out.println("MS1의 num1을 증가한 결과 : " + MS1.num1);
		
		MS2.plusnum1();
		System.out.println("MS2의 num1을 증가한 결과 : " + MS2.num1);
		System.out.println();
		
		MyStatic.num1++;
		System.out.println("클래스를 이용해 호출하여 num1을 증가한 결과 : " + MyStatic.num1);
		System.out.println();
		
		MS1.plusnum2();
		System.out.println("MS1의 num2를 증가한 결과  : " + MS1.num2);
		MS2.plusnum2();
		System.out.println("MS2의 num2를 증가한 결과 : " + MS2.num2);
		System.out.println();
		
		MS1.static_plusnum1();
		System.out.println("MS1의 num1을 증가한 결과  : " + MS1.num1);
		MS2.static_plusnum1();
		System.out.println("MS2의 num1을 증가한 결과  : " + MS2.num1);
		System.out.println();
		
		MS1.another_static_plusnum1();
		System.out.println("MS1의 num1을 증가한 결과  : " + MS1.num1);
		MS2.another_static_plusnum1();
		System.out.println("MS2의 num1을 증가한 결과  : " + MS2.num1);
	}