[JAVA 26] 자바 ② 소유 제한자 ( static )
2) 소유 제한자 ( static )
(1) static 이 붙으면 클래스 소유 , 붙지 않으면 객체 소유가 된다.
(2) 특징
① Class ( 클래스 ) 와 Constructor ( 생성자 ) 앞에는 붙지 못한다.
Memeber Variable ( 멤버 변수 ) 와 Method ( 메소드 ) 앞에만 붙을 수 있다.
error : illegal start of expression
에러 : 불법적인 표현이 시작되었다.
error : class , interface , or enum expected // (Enumeration ( 열거 타입 ) 나중에 하겠다.)
에러 : 클래스 , 인터페이스 , 또는 열거타입 이 예상된다.
② static method 내에서는 객체 생성 없이 static 자원을 호출 가능하다.
해당 자원에 클래스 이름이 생략이 된다.
③ Local Variable ( 지역변수 ) 에는 static 이 붙을수 없다.
오직 Member Variable ( 멤버 변수 ) 만이 소유의 대상이 된다.
④ 다른 클래스에서 static 자원을 호출할 때에는 클래스 이름을 생략할 수 없다.
1 2 3 4 5 6 7 8 9 10 11 12 | class StaticS1{ // static Study 1 static int i = 10; StaticS1(){ // static String name = "CIVIC"; // 불가능하다. } static void m(){ System.out.println("메소드 내용"); } } |
1 2 3 4 5 6 | class User1{ // User1 클래스에서 StaticS1 클래스의 자원을 사용한다. public static void main(String[] args){ System.out.println(" i : " + StaticS1.i); // 클래스.변수 StaticS1.m(); } } |
⑤ static 자원은 메모리에 오직 1개 생성이 된다.
해당 클래스의 모든 객체에서 공유 되어진다.
⑥ static 메소드에서는 this 와 super 을/를 사용할 수 없다.
error : non-static variable super cannot be referenced from a static context
에러 : static 문맥으로 부터 non-static 변수 super 를 참조 ( 언급 ) 할 수 없다.
this
error : non-static variable this cannot be referenced from a static context
error : non-static variable a cannot be referenced from a static context
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | class StaticS2{ int a; static int b; StaticS2(){ a++; b++; } public static void main(String[] args){ // String name = super.toString(); // 불가능 !! // System.out.println(" this.a : " + this.a); // 불가능 !! StaticS2 ss1 = new StaticS2(); StaticS2 ss2 = new StaticS2(); StaticS2 ss3 = new StaticS2(); System.out.println(" a : " + ss3.a); System.out.println(" 1. b : " + ss3.b); System.out.println(" 2. b : " + ss3.b); // static 변수는 객체로 호출해도 되고, 클래스로 호출해도 된다. } } |
여기서 문제 !
< 문제 : a 는 1 인데 , b 는 어째서 3일까?? >
비유를 하나 들어볼까 !
< 주의 : 이 비유가 static 공부에 방해가 될 수 있습니다. >
< 또한 혼란을 야기할 수 있습니다. >