static, non-static

민선규·2023년 3월 22일
0

JAVA

목록 보기
8/25
post-thumbnail

static(클래스 변수)

  • 클래스 내에 static 키워드가 붙은 변수이다.
  • JVM이 실행되면서 클래스가 로드 될 때 부터 프로그램이 종료될 때 까지 유지된다.
  • 클래스가 로드될 때 처음 한 번만 생성된다.
  • 모든 클래스에 공유된다.

non-static(인스턴스 변수)

  • 객체가 생성될 때 변수가 생성된다.
  • 객체가 사라지면 변수도 사라진다.
public class Test {
 
    public static void main(String[] args) {
 
        StaticTest staticTest1 = new StaticTest();
        StaticTest staticTest2 = new StaticTest();
 
        staticTest1.A = 10;
        staticTest1.B = 20;
 
        staticTest2.A = 30;
        staticTest2.B = 40;
 
 		//static -> 30
        System.out.println("static -> " + staticTest1.A);
        //static -> 20
        System.out.println("non static -> " + staticTest1.B);
        //static -> 30
        System.out.println("static -> " + staticTest2.A);
        //static -> 40
        System.out.println("non static -> " + staticTest2.B);
    }
}
 
class StaticTest {
 
     static int A;
     int B;
}

참고 문서 및 링크

0개의 댓글

관련 채용 정보