JAVA

자바 static

커피마시기 2023. 10. 10. 22:12

 

 

 

 

 

■  static

static은 고정된이란 의미를 가지고 있으며 Static 이라는 키워드를 사용하여 Static변수와 Static메소드를 만들 수 있다 

 

● static

  • 주로 클래스들이 할당
  • 모든 객체가 메모리를 공유
  • Garbage Collector 관여 X -> 프로그램의 종료시까지 메모리가 할당된 채로 존재
  • 객체의 생성 없이 호출이 가능

 

● heap

  • 주로 객체들이 할당
  • 메모리를 공유하지 않는다
  • Garbage Collector 관여 O

 

 


● 선언

public class Note1  {
	
	static int point = 1000;
	int point2 = 1000;
}

 

● 사용 예시

public class Main {

	public static void main(String[] args) {
		
	Note1 n1 = new Note1();
	Note1 n2 = new Note1();
	
	n1.point++;
	n1.point2++;
	
	System.out.println(n2.point);
	System.out.println(n2.point2);
	}
}

출력 결과

 

인스턴스 변수는 인스턴스가 생성될 때마다 생성되므로 각 각 다른 값을 가지지만 정적 변수는 하나의 저장공간을 공유하기 때문에 n2를 생성하더라도 n1에서 공유한 값을 가지게 된다.

 

 

 

 

● 정적(static) 메소드 사용 예시

public class Note2 {

	public static void disp1() {
		System.out.println("static 클래스 메소드 확인 테스트");
	}
	
	void disp2() {
		System.out.println("인스턴스 메소드 확인 테스트");
	}
}
public class Main {

	public static void main(String[] args) {
		
		Note2.disp1(); // static 인스턴스 생성하지 않아도 호출 가능
	
		Note2 note2 =  new Note2();  // 인스턴스 생성하여야 호출 가능
		note2.disp2();
	}
}

static 메소드 출력 결과

 

 

 

 

 


 

■  활용해보기

 

 

●  static으로 사용 할 point와  아이디,비밀번호 필드 생성

● 생성자와 메소드 result 만들어주었다

public class Note1  {
	
	static int point = 1000;
	private String userid;
	private String passwd;
	
	
	public Note1(String userid, String passwd) {
		this.userid = userid;
		this.passwd = passwd;
	}

	public void result() {
		System.out.println("아이디 : " + this.userid + " 비밀번호 : " + this.passwd + " 포인트 : " +  point);
	}
}

 

 

● 이후에 생성자의 userid와 passwd이 null이 아니면 static int point가 100씩 증가하도록 해주었다

	public Note1(String userid, String passwd) {
		this.userid = userid;
		this.passwd = passwd;
		
		if(userid != null && passwd != null) {
			System.out.println("확인되었습니다.");
			point += 100;
		}else {
			System.out.println("틀렸습니다.");
			point += 0;
		}
	}

 

 

● 이후 n1, n2를 통해 static으로 해준 point 값을 비교해보았고 n1에서의 point가 공유되어 n2에서 기존값에서 추가적으로 오른 결과를 볼 수 있었다

public class Main {

	public static void main(String[] args) {
		
	Note1 n1 = new Note1("1q2w", "1234");
	n1.result();
	
	Note1 n2 = new Note1("1q2w", "1234");
	n2.result();
	}
}

static int point 확인용 출력 결과

 

 

 

 


 

 

Today short review

 

이전에 배운것들과 static을 활용하여 미약하게나마 연습해보았는데 틀린부분이나 잘못 알고 있는 부분이 있다면 알려주시면 감사하겠습니다~!

'JAVA' 카테고리의 다른 글

자바 제네릭(Generic)  (0) 2023.10.16
자바 JDBC  (0) 2023.10.12
자바 인터페이스(Interface)  (0) 2023.10.06
자바 상속 extends  (0) 2023.09.29
자바 Map  (0) 2023.09.27