티스토리 뷰
728x90
static 이점
- static 키워드를 붙이면 자바는 메모리 할당을 딱 한번만 하게 되어 메모리 사용에 이점
- final static 사용시 한번 설정하면 값 변경을 할수 없음. 변경시 오류발생
static 예제
class Counter {
static int count = 0;
Counter() {
count++; // count는 더이상 객체변수가 아니므로 this를 제거하는 것이 좋다.
System.out.println(count); // this 제거
}
}
public class Sample {
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
}
}
- count 변수 앞에 static 표기시 count 변수가 공유되어 사용
static 메서드
class Counter {
static int count = 0;
Counter() {
count++;
System.out.println(count);
}
public static int getCount() {
return count;
}
}
public class Sample {
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
System.out.println(Counter.getCount()); // 스태틱 메서드는 클래스를 이용하여 호출
}
}
- 메서드 앞 static 키워드 붙이면 객체 생성없이 클래스를 통해 메서드를 직접 호출 가능
singleton pattern
- 싱글톤은 단 하나의 객체만을 생성하게 강제하는 패턴
- 즉 클래스를 통해 생성할 수 있는 객체는 Only One, 즉, 한 개만 되도록 만드는 것
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 출력
}
}
728x90
'Backend' 카테고리의 다른 글
java - abstract class (0) | 2023.02.17 |
---|---|
java - constructor (0) | 2023.02.15 |
java - inheritance (0) | 2023.02.15 |
java - 메서드 (0) | 2023.02.15 |
java - final (0) | 2023.02.14 |
250x250
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- docker container
- CentOS
- yml
- IntelliJ
- Private Repository
- build.gradle
- 의존성주입
- ubuntu
- docker-compose
- bulk
- docker
- xshell
- VirtualMachine
- mybatis
- VitualBox
- docker registry
- Singleton
- springboot
- DockerHub
- Settings
- netword
- WebService
- dockerfile
- Linux
- aws
- 단위테스트코드
- containerstorage
- 프로그래머스
- 순열
- container
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
글 보관함