1. static
class Counter {
int count = 0;
Counter() {
this.count++;
System.out.println(this.count);
}
}
public class HelloSpringApplication {
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
}
}
다음과 같은 코드가 있다고 가정할때 위 코드는 다음과 같은 결과값이 나온다.
1
1
서로다른 객체를 생성하여 다른 객체를 가르키고 있기 때문에 발생하는 결과이다.
다음 예제를 살펴보자
class Counter {
static int count = 0;
Counter() {
count++;
System.out.println(count);
}
}
public class HelloSpringApplication {
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
}
}
결과값
1
2
static 넣었더니 count값이 공유되는 것을 알 수 있다.
대체로 static은 메모리의 효율을 높여주는데, 메모리의 효율보다는 공유의 목적으로 더 많이 사용된다.
2. static 메소드
class Counter {
static int count = 0;
Counter() {
count++;
System.out.println(count);
}
public static int getCount() {
return count;
}
}
public class HelloSpringApplication {
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
System.out.println(Counter.getCount()); // 스태틱 메서드는 클래스를 이용하여 호출
}
}
결과값
1
2
2
static 메소드는 Counter.getCount() 와 같이 객체 생성 없이 클래스를 통해 메소드는 직접 호출할 수 있다.
※ 스태틱 메소드 안에서는 객체변수 접근이 불가능 하다. 위 예에서는 count 변수가 static 변수이기 때문에 스태틱 메소드(static method)에서 접근이 가능하다.
3. 싱글톤 패턴
싱글톤 패턴이랑 단 하나의 객체만을 생성하게 하도록 하는 패턴이다. 즉, 클래스를 통해 생성할 수 있는 객체는 단 한개만 되도록 만드는 것이 싱글톤이다.
다음 코드를 살펴보자.
class Singleton {
private static Singleton one;
private Singleton() {
}
public static Singleton getInstance() {
if(one==null) {
one = new Singleton();
}
return one;
}
}
public class Sample {
public static void main(String[] args) {
Singleton singleton1 = Singleton.getInstance();
Singleton singleton2 = Singleton.getInstance();
System.out.println(singleton1 == singleton2); // true 출력
}
}
결과값을 true를 출력하는 것을 알 수 있다.
이를 통해 singleton1과 singleton2가 같은 객체를 가리키고 있다는 것을 알 수 있다.
'[JAVA] 기본 문법' 카테고리의 다른 글
[JAVA] 제네릭 프로그래밍 (0) | 2023.02.07 |
---|---|
[JAVA] 자바 스트림 (0) | 2023.02.06 |
[JAVA] 어노테이션 (0) | 2022.08.06 |
[JAVA] Enum (0) | 2022.07.30 |
[JAVA] 생성자 (0) | 2022.07.29 |
[JAVA] 접근 제어자 (0) | 2022.07.24 |
[JAVA] 자료형-문자열 (0) | 2022.07.17 |
[JAVA] 자료형-숫자 (0) | 2022.07.17 |