728x90
생성자가 여러 차례 호출되더라도 실제로 생성되는 객체는 하나이고, 최초 생성 이후에 호출된 생성자는 최초의 생성자가 생성한 객체를 리턴
public class Manager {
private static Manager = manager = new Manager();
private Manager() {}
public static Manager getManager() {
return manager;
}
- 기본 생성자를 private으로 → 외부에서 인스턴스를 새로 생성할 수 없음
- getManager() 메서드는 인스턴스 생성과 상관없이 호출할 수 있어야 하기 때문에 반드시 static
용도/쓰임
여러 클래스에서 동시에 공유할 때
ex. 게임 - score
cf. static class와 차이: Singleton=한 번이라도 객체를 생성 → 인스턴스
static class: 인스턴스를 생성X
ex) Math.____ : 객체 생성 필요X
- static class는 static 변수, static 메소드만 O
Static
static 영역에서는 non-static 영역을 직접 접근이 불가능
non-static 영역에서는 static 영역에 대한 접근이 가능
public class Main {
String str = "예시"; //인스턴스 변수 -> new Main()이 만들어져야 사용 가능
public static void main(String[] args) {
System.out.println(str);
}
public class Main {
static String str = "문장"; //이미 메모리에 올라가 있음
public void print() {
System.out.println(str);
}
728x90
'Java' 카테고리의 다른 글
[자바/Java] 제네릭 Generics (0) | 2022.07.27 |
---|---|
[자바/Java] 클래스 다형성(Polymorphism) (0) | 2022.07.25 |
[자바/Java] 클래스(Class), 상속, 생성자(Constructor), 오버라이딩(Override) (0) | 2022.07.25 |
[자바/Java] 배열, 1차원 배열, 2차원 배열 정리 (0) | 2022.07.23 |
자바 정규식 (regex) / 정규식 테스트 (0) | 2022.04.29 |