Static

소정·2023년 1월 26일
0

Java

목록 보기
12/23

Static 변수란?

  • static은 멤버변수 / 멤버함수 / 이너클래스에만 붙일 수 있다
  • static 변수는 모든 인스턴스(어떤종류의 객체)가 공유함
  • static변수는 객체에 있지 않고 클래스에 오직 하나만 존재 : 클래스변수라고도 불림
  • 클래스명.b 라고 쓰는 것이 조금 더 합리적이다
  • 객체생성과 상관없이 존재하는 변수
  • static메소드 안에서는 static멤버 변수만 쓸수 있다

public class Main {
	
	public static void main(String[] args) {
		
		//지역변수에는 static키워드 사용 할 수 없다
		//static int a;
		
		Test.b = 20;
		
		Test t1 = new Test(15,20);
		Test t2 = new Test(10,40);
		Test t3 = new Test(50,60);
		
		System.out.println(t1.a);
		System.out.println(t2.a);
		System.out.println(t3.a);
		
		System.out.println(t1.b);
		System.out.println(t2.b);
		System.out.println(t3.b);
		
		
	}
	
}


public class Test {

	public int a; //멤버변수 -> 객체마다 변수가 존재
	
	public static int b; //정적(static) 멤버변수 -> Test클래스에 1개만 존재
	//객체 안에 있는 것처럼 보이지만 객체 밖에 있다
	
	//생성자
	public Test(int a, int b) {
		this.a = a;
		this.b = b;
	}
	
}

참고
  • static 함수 안에선 static 멤버변수만 쓸수있음
  • static은 객체가 없어도 쓸수 있는 함수 안에선 일반 인스턴스 멤버/메소드는 객체가 있을때만 존재 할 수 있기 때문에 쓸수 없다
  • static함수 안에선 this 키워드 활용 불가 this는 객체 안에 있는 키워드 이기 때문에 오류

public class Test {

	public int a; //멤버변수 -> 객체마다 변수가 존재 ,인스턴스(어떤종류의 객체)변수라고 부름
	
	public static int b; //정적(static) 멤버변수 -> Test클래스에 1개만 존재, 클래스변수라고도 부름
	//객체 안에 있는 것처럼 보이지만 객체 밖에 있다
	
	//생성자
	public Test(int a, int b) {
		this.a = a;
		this.b = b;
	}
	
	//일반 메소드 - instance method
	void aaa() {
		System.out.println("일반 메소드");
		System.out.println("a: "+this.a); //일반변수
		System.out.println("b: "+this.b); //static변수
	}
	
	//static 메소드 - class method, 객체 생성과 상관없이 사용
	static void bbb() {
		System.out.println("static 메소드");
		System.out.println("a: "+this.a); //일반변수 this는 객체 안에 있는 키워드 이기 때문에 오류
		System.out.println("b: "+this.b); //static변수
	}
	
	
}

static 초기화 블록

클래스가 처음 사용될 때 딱 한번 초기화 함
인스턴트 초기화는 사용할 때마다 호출

public class Main {
	
	public static void main(String[] args) {
    
    	new Second(); 
		new Second();
		new Second();
		
		System.out.println(Second.b);
    
    }
}



public class Second {
	
	int a;
	static int b;
	
	//초기화 블록 -> 인스턴스 초기화 블록
	{
		System.out.println("instance 초기화 블록");
		a=10;
		//b=50; //권장하지않음
	}
	
	//static 초기화 블록
	static {
		System.out.println("static 초기화 블록");
		//a = 10; //인스턴스 변수 초기화 불가능
		b = 50;
	}
	
}


Inner클래스 vs local(내부)클래스

Inner class

  • 클래스 안에 클래스가 있는 것
  • 이너 클래스는 아웃클래스명으로 인식가능
  • 객체를 안전하게 만들기 위해서 사용하는 기법
    외부에서 아웃터객체없이 마음대로 생성하지 못하도록 문법적으로 막는 기법
    결국 아웃터 클래스를 생성하지 않으면 이너 클래스를 객체로 생성할 수 없도록 함으로써 잘못된 객체사용을 막아주기 위함
  • 이너 클래스 4가지 특징
  1. 외부(다른 클래스)에서 아웃터 클래스명 없이는 인식 불가
  2. 이너 클래스는 아웃클래스명으로 인식가능하더라도 직접 객체생성이 불가능함
  3. 이너 클래스는 아웃터 클래스 안에서만 객체 생성 가능한 클래스
  4. 이너 클래스 안에서 아웃터 클래스의 멤버를 마음대로 사용 가능
    당연히 아웃터에선 이너 멤버 맘대로 사용 불가

public class Main {

	public static void main(String[] args) {

		//일반 클래스는 간단하게 객체로 만들어짐
		Test t = new Test();
		t.show();
		
		//클래스 안에 클래스를 설계하는 inner class
		
		//이너 클래스는 아웃터명 없이는 인식 불가
		
		//이너 클래스는 아웃클래스명으로 인식가능하더라도 직접 객체생성이 불가능함
		//Test.Nice nice =new Test.Nice();
		
		//이너클래스를 객체로 만들어 사용하고싶다면...
		//outter 객체에서 이너클래스 객체를 만들어서 리턴해 달라고 요첨 = 메소드 호출
		Test.Nice nice = t.makeInnerClassObject();
		nice.aaa();
		
	}

}


public class Test {
	
	int a = 10;
	
	void show() {
		System.out.println("show : "+a);
	}//
	
	//이너 클래스 객체로 생성하여 리턴해주는 메소드
	Nice makeInnerClassObject() {
		Nice n =new Nice();
		
		return n;
	}
	
	//class 안에 또 다른 class를 설계
	//inner 클래스
	class Nice {
		
		int k=100;
		
		void aaa() {
			System.out.println("Naic... " + k);
			
			//아웃터 멤버변수,함수 사용
			a = 200;
			System.out.println("아웃터 a : "+ a);
			show();
		}
		
	}
	
	
}

local class

  • 그 메소드가 실행중일 때만 잠시 일회용처럼 사용하는 객체를 만들고 싶을 때 사용.
  • '익명 클래스'라는 것을 사용할 때 쓴다.

public class Localclass {
	
	int g = 10;
	
	void aaa() {
		
		int a = 50; //지역변수 - 다른 지역에서는 사용 불가
		
		//메소드 영역 안에 클래스 설계
		//Local class [지역클래스, 내장클래스, 내부클래스]
		//설계된 지역 안에서만 인식 가능한 클래스(설계도)
		class Good{
			int n=60;
			
			void show() {
				System.out.println("Good...Show");
				System.out.println(a);// 지역변수는 error final 상수면 가능
				//상수는 method 영역에 들어가기 때문 
			}
		}
		
		Good good = new Good();
		good.show();
		
	}
	
	
	void bbb() {
		g = 1000;
		//a =100; // error
		
		//Good good = new Good(); //error - 인식 불가능
	}
	
	
}
profile
보조기억장치

0개의 댓글