[JAVA] Static

Y_Y·2022년 8월 12일
1

JAVA

목록 보기
2/3

많이 헷갈리는 Static 정리해보자!

Static

JAVA에서 Static은 프로그램 시작 시 메모리에 할당되어 프로그램이 종료될 때 까지 사용이 되는 것을 의미하는 것으로, 모든 객체가 공유하는 메모리라는 장점이 있지만, 자주 사용될 경우 지속적인 메모리 할당으로 과부하를 줄 수 있다.

Static 변수

  • 클래스 변수이다. (공유 변수)
  • 객체의 생성 없이 변수에 접근이 가능하다.
public class MainClass {
	public static void main(String[] args) {
    	ExampleStatic.name = "Test";
        ExampleStatic example = new ExampleStatic();
        example.name = "Test2"; // 지향하지 않는 방식
    }
}

public class ExampleStatic {
	public static String name = "Example"
	
}

Static 메서드

  • 객체의 생성 없이 호출이 가능하다
    자주 사용되는 메서드의 경우 java class의 유틸리티와 같이 static형으로 선언하는 것이 좋다.
    Math.max() 와 같이 java.util.Math가 대표적인 유형이다.
  • Static 메서드에서 접근하기 위한 변수는 반드시 Static 변수여야 한다.
    -> Static 변수는 객체를 생성한 후 호출할 수 있는 변수인데, Static 메서드는 프로그램 시작시 메모리에 자동 할당이 되기 때문에 할당되지 않은 메모리 접근이 이루어져 에러가 발생한다.
import java.util.Math

public class ExamplePrint {
	private static String name = "Eu";
    private String name2 = "Gene";
    
    public static void printMax(int x, int y) {
    	System.out.println(Math.max(x,y));
    }
    
    public static void printName(){
    	System.out.println(name); 
        // System.out.println(name2); // 불가능한 호출
    }
}

Ref. MangKyu's Diary

profile
남을 위해(나를 위해) 글을 쓰는 Velog

0개의 댓글