본문 바로가기
Language/JAVA

[JAVA] 08일차. 클래스와 객체2 (3), (4)

by 전전긍긍 2022. 2. 26.

👀202202018 공부기록

 

📍본 포스팅은 인프런-Do it! 자바 프로그래밍 입문 강의를 바탕으로 작성함을 알립니다.

 

[무료] Do it! 자바 프로그래밍 입문 - 인프런 | 강의

비전공자, 문과생도 무릎을 ‘탁!’ 치며 이해하는 20년 경력 명강사의 자바 강의!, - 강의 소개 | 인프런...

www.inflearn.com


15. 클래스와 객체2 (3) - static 변수

stiatic 변수 : 변수도 사용하고 메소드도 사용 가능함. 여러 개의 인스턴스가 같은 메모리의 값을 공유하기 위해 사용

static예약어 자료형 변수이름;
  • static 변수는 동적 메모리인 heap메모리에 생성된다. 객체가 생성될 때는 메모리를 할당을 받고 객체가 소멸되면 메모리가 사라지는데 static 변수는 공유되는 메모리를 따로 쓴다.
  • static 변수는 전체 프로그램이 메모리에 load 될 때 할당받는 영역이다. (static이 들어가는 메모리에는 상수와 리터럴도 들어간다.)
  • static 변수는 인스턴스의 생성과 관계없이 클래스 이름으로 직접 참조하기 때문에 클래스 변수라고도 한다.

* new할 때 할당받는 것은 인스턴스 변수(멤버 변수)

아래 코드에서 serialNum이 static 변수이다. serialNum을 static으로 선언하면 모든 student 인스턴스에 대해 하나의 변수로 유지되고 이러한 변수를 class 변수라고 한다.

package staticex;

public class Student {

	//외부에서 가져다 쓸 수 없기 때문
	private static int serialNum = 10000;
	
	//static 메소드
	public static int getSerialNum() {
		int i = 10; //지역변수, 이 메소드가 호출될 때 스택에 생성
		i++;
		System.out.println(i);
		
		//studentID = 10; //멤버변수(필드, 인스턴스 변수)생성되지 않기 때문에 위험
		//static메서드에서는 멤버변수를 사용할 수 없다.
		return serialNum; //static변수, 클래스 변수
	}

	int studentID;
	String studentName;
	
	public Student() {
		serialNum++;
		studentID = serialNum;
	}
}
package staticex;

public class StudentTest1 {

	public static void main(String[] args) {

		Student studentJ = new Student();
		System.out.println(studentJ.studentID); //10001
		
		Student studentT = new Student();
		System.out.println(studentT.studentID); //10002
		
		Student studentK = new Student();
		System.out.println(studentK.studentID); //10003
		
		System.out.println(Student.getSerialNum()); //10003
		System.out.println(Student.getSerialNum()); //10003
	}

}

📍변수의 유효범위


16. 클래스와 객체2 (4) - singleton 변수

singleton 변수는 어떤 클래스가 최초 한 번만 메모리를 할당하고(Static), 그 메모리에 객체를 만들어 사용하는 디자인 패턴을 의미한다. 즉, 생성자의 호출이 반복적으로 이뤄져도 실제로 생성되는 객체는 최초 생성된 객체를 반환해주는 것.

package singleton;

public class Company {

	//전체에서 유일하게 사용할 인스턴스_값이 함부로 변경되면 안됨
	//여러 개 있을 거 아니고 단 하나만 존재할 것이기 때문에 static
	private static Company instance = new Company();
	//생성자_외부에서 생성자 호출X
	private Company(){}
	
	//가져다 쓸 퍼블릭한 메소드
	//객체를 선언하지 않고 사용하기 위해서 static 사용->클래스 이름을 참조해서 사용
	public static Company getInstance() {
		if(instance == null)
			instance = new Company(); //객체를 생성해서 할당
		return instance;
	}
	
}
package singleton;

public class CompanyTest {

	public static void main(String[] args) {

		Company c1 = Company.getInstance();
		
		Company c2 = Company.getInstance();
		
		//주소값 출력
		System.out.println(c1); //singleton.Company@4517d9a3
		System.out.println(c2); //singleton.Company@4517d9a3
	}

}

[참고 자료]

singleton 참고

https://elfinlas.github.io/2019/09/23/java-singleton/

 

Java에서 싱글톤(Singleton) 패턴을 사용하는 이유와 주의할 점

Java에서 Singleton 패턴이란?Singleton(이하 싱글톤) 패턴은 자바에서 많이 사용한다.먼저 싱글톤이란 어떤 클래스가 최초 한번만 메모리를 할당하고(Static) 그 메모리에 객체를 만들어 사용하는 디자

elfinlas.github.io